Skip to content

Commit 69492df

Browse files
openapi3: typed context errors for Validate() wrapper chain (#1183)
* feat(openapi3): typed context errors for Validate() wrapper chain Replaces the 14 fmt.Errorf wrap sites in Validate() with three typed error types carrying their context as structured fields: - SectionContextError{Section, Cause} — wraps an error inside one of the top-level document sections (info, paths, components, security, servers, tags, externalDocs, webhooks, jsonSchemaDialect) - PathContextError{Path, Cause} — wraps an error inside a specific path - OperationContextError{Method, Cause} — wraps an error inside a specific HTTP-method operation Continues the typed-validation-error work from #1166 and #1180: those PRs typed the leaf errors; this one types the wrapper layers that carry doc-tree position around them. Why: today, callers that want to render context separately (which section a finding lives in, which path, which operation) have to parse the rendered error string with regex. errors.As against typed wrappers is the structured equivalent. Backward compatibility: Error() strings are byte-identical to the fmt.Errorf wrappers they replace. Existing consumers parsing the rendered text continue to work unchanged. The typed extraction is purely additive. Wrap sites converted: - openapi3.go: 9 sections (info, paths, components, security, servers, tags, externalDocs, webhooks, jsonSchemaDialect) - paths.go: per-path wrapper (PathContextError) - path_item.go: per-operation wrapper (OperationContextError) - operation.go, tag.go, schema.go: 3 additional externalDocs sites (also use SectionContextError{Section: "external docs"}) Tests cover Error() format byte-stability, Unwrap chain walking, errors.As extraction from a three-layer chain (section + path + operation), and arbitrary non-typed inner causes. All existing tests pass unchanged across openapi2, openapi3, openapi3conv, openapi3filter, openapi3gen, and the routers — confirming the rendered strings are stable. .github/docs/openapi3.txt regenerated via docs.sh. * refactor(openapi3): rename context errors to *ValidationError Addresses review feedback on #1183: - SectionContextError -> SectionValidationError - PathContextError -> PathValidationError - OperationContextError -> OperationValidationError The new names tie these positional wrappers to the ValidationError family they belong to (base ValidationError, cluster types, leaves). Also renames the file to sit in that namespace: section_context_error.go -> validation_error_context.go (+ _test.go). No behavior change: Error() strings and Unwrap() chains are untouched. .github/docs/openapi3.txt regenerated. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
1 parent 0a89925 commit 69492df

9 files changed

Lines changed: 213 additions & 16 deletions

File tree

‎.github/docs/openapi3.txt‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1412,6 +1412,21 @@ type OperationResponsesRequired struct{ ValidationError }
14121412

14131413
func (e *OperationResponsesRequired) As(target any) bool
14141414

1415+
type OperationValidationError struct {
1416+
Method string
1417+
Cause error
1418+
}
1419+
OperationValidationError wraps an error originating inside a specific
1420+
HTTP-method operation under a path. Method is the uppercase method (GET,
1421+
POST, etc.).
1422+
1423+
Use errors.As(err, &ove) to extract the method from a validation error chain
1424+
without parsing the rendered message.
1425+
1426+
func (e *OperationValidationError) Error() string
1427+
1428+
func (e *OperationValidationError) Unwrap() error
1429+
14151430
type Origin struct {
14161431
Key *Location `json:"key,omitempty" yaml:"key,omitempty"`
14171432
Fields map[string]Location `json:"fields,omitempty" yaml:"fields,omitempty"`
@@ -1615,6 +1630,20 @@ type PathParametersError struct {
16151630

16161631
func (e *PathParametersError) Error() string
16171632

1633+
type PathValidationError struct {
1634+
Path string
1635+
Cause error
1636+
}
1637+
PathValidationError wraps an error originating inside a specific path. Path
1638+
is the path template as it appears in the document (e.g. "/users/{id}").
1639+
1640+
Use errors.As(err, &pve) to extract the path from a validation error chain
1641+
without parsing the rendered message.
1642+
1643+
func (e *PathValidationError) Error() string
1644+
1645+
func (e *PathValidationError) Unwrap() error
1646+
16181647
type Paths struct {
16191648
Extensions map[string]any `json:"-" yaml:"-"`
16201649
Origin *Origin `json:"-" yaml:"-"`
@@ -2507,6 +2536,22 @@ func (m Schemas) JSONLookup(token string) (any, error)
25072536
func (schemas *Schemas) UnmarshalJSON(data []byte) (err error)
25082537
UnmarshalJSON sets Schemas to a copy of data.
25092538

2539+
type SectionValidationError struct {
2540+
Section string
2541+
Cause error
2542+
}
2543+
SectionValidationError wraps an error originating inside one of the
2544+
top-level OpenAPI document sections (info, paths, components, security,
2545+
servers, tags, externalDocs, webhooks, jsonSchemaDialect). Section is the
2546+
OpenAPI field name as it appears in the document root.
2547+
2548+
Use errors.As(err, &sve) to extract the section context from a validation
2549+
error chain without parsing the rendered message.
2550+
2551+
func (e *SectionValidationError) Error() string
2552+
2553+
func (e *SectionValidationError) Unwrap() error
2554+
25102555
type SecurityRequirement map[string][]string
25112556
SecurityRequirement is specified by OpenAPI/Swagger standard version 3. See
25122557
https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#security-requirement-object

‎openapi3/openapi3.go‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -280,14 +280,14 @@ func (doc *T) Validate(ctx context.Context, opts ...ValidationOption) error {
280280

281281
var wrap func(error) error
282282

283-
wrap = func(e error) error { return fmt.Errorf("invalid components: %w", e) }
283+
wrap = func(e error) error { return &SectionValidationError{Section: "components", Cause: e} }
284284
if v := doc.Components; v != nil {
285285
if err := v.Validate(ctx); err != nil {
286286
return wrap(err)
287287
}
288288
}
289289

290-
wrap = func(e error) error { return fmt.Errorf("invalid info: %w", e) }
290+
wrap = func(e error) error { return &SectionValidationError{Section: "info", Cause: e} }
291291
if v := doc.Info; v != nil {
292292
if err := v.Validate(ctx); err != nil {
293293
return wrap(err)
@@ -296,7 +296,7 @@ func (doc *T) Validate(ctx context.Context, opts ...ValidationOption) error {
296296
return wrap(newInfoRequired())
297297
}
298298

299-
wrap = func(e error) error { return fmt.Errorf("invalid paths: %w", e) }
299+
wrap = func(e error) error { return &SectionValidationError{Section: "paths", Cause: e} }
300300
if v := doc.Paths; v != nil {
301301
if err := v.Validate(ctx); err != nil {
302302
return wrap(err)
@@ -305,35 +305,35 @@ func (doc *T) Validate(ctx context.Context, opts ...ValidationOption) error {
305305
return wrap(newPathsRequired())
306306
}
307307

308-
wrap = func(e error) error { return fmt.Errorf("invalid security: %w", e) }
308+
wrap = func(e error) error { return &SectionValidationError{Section: "security", Cause: e} }
309309
if v := doc.Security; v != nil {
310310
if err := v.Validate(ctx); err != nil {
311311
return wrap(err)
312312
}
313313
}
314314

315-
wrap = func(e error) error { return fmt.Errorf("invalid servers: %w", e) }
315+
wrap = func(e error) error { return &SectionValidationError{Section: "servers", Cause: e} }
316316
if v := doc.Servers; v != nil {
317317
if err := v.Validate(ctx); err != nil {
318318
return wrap(err)
319319
}
320320
}
321321

322-
wrap = func(e error) error { return fmt.Errorf("invalid tags: %w", e) }
322+
wrap = func(e error) error { return &SectionValidationError{Section: "tags", Cause: e} }
323323
if v := doc.Tags; v != nil {
324324
if err := v.Validate(ctx); err != nil {
325325
return wrap(err)
326326
}
327327
}
328328

329-
wrap = func(e error) error { return fmt.Errorf("invalid external docs: %w", e) }
329+
wrap = func(e error) error { return &SectionValidationError{Section: "external docs", Cause: e} }
330330
if v := doc.ExternalDocs; v != nil {
331331
if err := v.Validate(ctx); err != nil {
332332
return wrap(err)
333333
}
334334
}
335335

336-
wrap = func(e error) error { return fmt.Errorf("invalid webhooks: %w", e) }
336+
wrap = func(e error) error { return &SectionValidationError{Section: "webhooks", Cause: e} }
337337
for _, name := range componentNames(doc.Webhooks) {
338338
pathItem := doc.Webhooks[name]
339339
if pathItem == nil {
@@ -344,7 +344,7 @@ func (doc *T) Validate(ctx context.Context, opts ...ValidationOption) error {
344344
}
345345
}
346346

347-
wrap = func(e error) error { return fmt.Errorf("invalid jsonSchemaDialect: %w", e) }
347+
wrap = func(e error) error { return &SectionValidationError{Section: "jsonSchemaDialect", Cause: e} }
348348
if doc.JSONSchemaDialect != "" {
349349
u, err := url.Parse(doc.JSONSchemaDialect)
350350
if err != nil {

‎openapi3/operation.go‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ package openapi3
33
import (
44
"context"
55
"encoding/json"
6-
"fmt"
76
"maps"
87
"strconv"
98

@@ -213,7 +212,7 @@ func (operation *Operation) Validate(ctx context.Context, opts ...ValidationOpti
213212

214213
if v := operation.ExternalDocs; v != nil {
215214
if err := v.Validate(ctx); err != nil {
216-
return fmt.Errorf("invalid external docs: %w", err)
215+
return &SectionValidationError{Section: "external docs", Cause: err}
217216
}
218217
}
219218

‎openapi3/path_item.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -209,7 +209,7 @@ func (pathItem *PathItem) Validate(ctx context.Context, opts ...ValidationOption
209209
for _, method := range componentNames(operations) {
210210
operation := operations[method]
211211
if err := operation.Validate(ctx); err != nil {
212-
return fmt.Errorf("invalid operation %s: %w", method, err)
212+
return &OperationValidationError{Method: method, Cause: err}
213213
}
214214
}
215215

‎openapi3/paths.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ func (paths *Paths) Validate(ctx context.Context, opts ...ValidationOption) erro
110110
}
111111

112112
if err := pathItem.Validate(ctx); err != nil {
113-
return fmt.Errorf("invalid path %s: %w", path, err)
113+
return &PathValidationError{Path: path, Cause: err}
114114
}
115115
}
116116

‎openapi3/schema.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1878,7 +1878,7 @@ func (schema *Schema) validate(ctx context.Context, stack []*Schema) ([]*Schema,
18781878

18791879
if v := schema.ExternalDocs; v != nil {
18801880
if err := v.Validate(ctx); err != nil {
1881-
return stack, fmt.Errorf("invalid external docs: %w", err)
1881+
return stack, &SectionValidationError{Section: "external docs", Cause: err}
18821882
}
18831883
}
18841884

‎openapi3/tag.go‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ package openapi3
33
import (
44
"context"
55
"encoding/json"
6-
"fmt"
76
"maps"
87
)
98

@@ -91,7 +90,7 @@ func (t *Tag) Validate(ctx context.Context, opts ...ValidationOption) error {
9190

9291
if v := t.ExternalDocs; v != nil {
9392
if err := v.Validate(ctx); err != nil {
94-
return fmt.Errorf("invalid external docs: %w", err)
93+
return &SectionValidationError{Section: "external docs", Cause: err}
9594
}
9695
}
9796

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package openapi3
2+
3+
import "fmt"
4+
5+
// SectionValidationError wraps an error originating inside one of the
6+
// top-level OpenAPI document sections (info, paths, components,
7+
// security, servers, tags, externalDocs, webhooks, jsonSchemaDialect).
8+
// Section is the OpenAPI field name as it appears in the document
9+
// root.
10+
//
11+
// Use errors.As(err, &sve) to extract the section context from a
12+
// validation error chain without parsing the rendered message.
13+
type SectionValidationError struct {
14+
Section string
15+
Cause error
16+
}
17+
18+
func (e *SectionValidationError) Error() string {
19+
return fmt.Sprintf("invalid %s: %v", e.Section, e.Cause)
20+
}
21+
22+
func (e *SectionValidationError) Unwrap() error { return e.Cause }
23+
24+
// PathValidationError wraps an error originating inside a specific path.
25+
// Path is the path template as it appears in the document (e.g.
26+
// "/users/{id}").
27+
//
28+
// Use errors.As(err, &pve) to extract the path from a validation
29+
// error chain without parsing the rendered message.
30+
type PathValidationError struct {
31+
Path string
32+
Cause error
33+
}
34+
35+
func (e *PathValidationError) Error() string {
36+
return fmt.Sprintf("invalid path %s: %v", e.Path, e.Cause)
37+
}
38+
39+
func (e *PathValidationError) Unwrap() error { return e.Cause }
40+
41+
// OperationValidationError wraps an error originating inside a specific
42+
// HTTP-method operation under a path. Method is the uppercase method
43+
// (GET, POST, etc.).
44+
//
45+
// Use errors.As(err, &ove) to extract the method from a validation
46+
// error chain without parsing the rendered message.
47+
type OperationValidationError struct {
48+
Method string
49+
Cause error
50+
}
51+
52+
func (e *OperationValidationError) Error() string {
53+
return fmt.Sprintf("invalid operation %s: %v", e.Method, e.Cause)
54+
}
55+
56+
func (e *OperationValidationError) Unwrap() error { return e.Cause }
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
package openapi3
2+
3+
import (
4+
"errors"
5+
"fmt"
6+
"testing"
7+
8+
"github.com/stretchr/testify/require"
9+
)
10+
11+
// Error() text format: "invalid <section>: <inner>" — byte-identical to
12+
// the fmt.Errorf wrapper this type replaced.
13+
func TestSectionValidationError_Error(t *testing.T) {
14+
inner := errors.New("value of version must be a non-empty string")
15+
e := &SectionValidationError{Section: "info", Cause: inner}
16+
require.Equal(t, "invalid info: value of version must be a non-empty string", e.Error())
17+
}
18+
19+
// Unwrap returns the inner error so errors.Is / errors.As walk the chain.
20+
func TestSectionValidationError_Unwrap(t *testing.T) {
21+
sentinel := errors.New("sentinel")
22+
e := &SectionValidationError{Section: "components", Cause: sentinel}
23+
require.True(t, errors.Is(e, sentinel))
24+
}
25+
26+
func TestPathValidationError_Error(t *testing.T) {
27+
inner := errors.New("bad path item")
28+
e := &PathValidationError{Path: "/users/{id}", Cause: inner}
29+
require.Equal(t, "invalid path /users/{id}: bad path item", e.Error())
30+
}
31+
32+
func TestPathValidationError_Unwrap(t *testing.T) {
33+
sentinel := errors.New("sentinel")
34+
e := &PathValidationError{Path: "/x", Cause: sentinel}
35+
require.True(t, errors.Is(e, sentinel))
36+
}
37+
38+
func TestOperationValidationError_Error(t *testing.T) {
39+
inner := errors.New("bad operation")
40+
e := &OperationValidationError{Method: "GET", Cause: inner}
41+
require.Equal(t, "invalid operation GET: bad operation", e.Error())
42+
}
43+
44+
func TestOperationValidationError_Unwrap(t *testing.T) {
45+
sentinel := errors.New("sentinel")
46+
e := &OperationValidationError{Method: "POST", Cause: sentinel}
47+
require.True(t, errors.Is(e, sentinel))
48+
}
49+
50+
// Three-layer chain (section + path + operation) is the typical shape
51+
// for a schema-deep validation error inside paths. errors.As against
52+
// each cluster pulls the corresponding context independently of the
53+
// others; nothing depends on the order in which the layers were
54+
// wrapped.
55+
func TestSectionPathOperationChain_AsExtraction(t *testing.T) {
56+
leaf := errors.New("field const is for OpenAPI >=3.1")
57+
chain := &SectionValidationError{
58+
Section: "paths",
59+
Cause: &PathValidationError{
60+
Path: "/thing",
61+
Cause: &OperationValidationError{
62+
Method: "GET",
63+
Cause: leaf,
64+
},
65+
},
66+
}
67+
68+
var sve *SectionValidationError
69+
require.True(t, errors.As(chain, &sve))
70+
require.Equal(t, "paths", sve.Section)
71+
72+
var pve *PathValidationError
73+
require.True(t, errors.As(chain, &pve))
74+
require.Equal(t, "/thing", pve.Path)
75+
76+
var ove *OperationValidationError
77+
require.True(t, errors.As(chain, &ove))
78+
require.Equal(t, "GET", ove.Method)
79+
80+
// And the leaf is still reachable via errors.Is.
81+
require.True(t, errors.Is(chain, leaf))
82+
83+
// And the rendered string concatenates the layers exactly as the
84+
// previous fmt.Errorf chain did.
85+
require.Equal(t,
86+
"invalid paths: invalid path /thing: invalid operation GET: field const is for OpenAPI >=3.1",
87+
chain.Error(),
88+
)
89+
}
90+
91+
// Mixed: a SectionValidationError wrapping an arbitrary non-typed error
92+
// still renders correctly. Guards against the typed wrapper changing
93+
// behaviour when the underlying error is not one of our cluster types.
94+
func TestSectionValidationError_WrappingArbitrary(t *testing.T) {
95+
inner := fmt.Errorf("third-party error: %w", errors.New("x"))
96+
e := &SectionValidationError{Section: "webhooks", Cause: inner}
97+
require.Equal(t, "invalid webhooks: third-party error: x", e.Error())
98+
}

0 commit comments

Comments
 (0)