Skip to content

Commit

Permalink
fix: wrap the error that came back from the callback (#674) (#675)
Browse files Browse the repository at this point in the history
  • Loading branch information
micronull authored Nov 22, 2022
1 parent 4a7405d commit 0d3c179
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 6 deletions.
14 changes: 8 additions & 6 deletions openapi3/schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -1298,29 +1298,31 @@ func (schema *Schema) visitJSONString(settings *schemaValidationSettings, value
}

// "format"
var formatErr string
var formatStrErr string
var formatErr error
if format := schema.Format; format != "" {
if f, ok := SchemaStringFormats[format]; ok {
switch {
case f.regexp != nil && f.callback == nil:
if cp := f.regexp; !cp.MatchString(value) {
formatErr = fmt.Sprintf(`string doesn't match the format %q (regular expression "%s")`, format, cp.String())
formatStrErr = fmt.Sprintf(`string doesn't match the format %q (regular expression "%s")`, format, cp.String())
}
case f.regexp == nil && f.callback != nil:
if err := f.callback(value); err != nil {
formatErr = err.Error()
formatErr = err
}
default:
formatErr = fmt.Sprintf("corrupted entry %q in SchemaStringFormats", format)
formatStrErr = fmt.Sprintf("corrupted entry %q in SchemaStringFormats", format)
}
}
}
if formatErr != "" {
if formatStrErr != "" || formatErr != nil {
err := &SchemaError{
Value: value,
Schema: schema,
SchemaField: "format",
Reason: formatErr,
Reason: formatStrErr,
Origin: formatErr,
}
if !settings.multiError {
return err
Expand Down
17 changes: 17 additions & 0 deletions openapi3/schema_formats_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ package openapi3

import (
"context"
"errors"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

Expand Down Expand Up @@ -58,3 +60,18 @@ func TestIssue430(t *testing.T) {
}
}
}

func TestFormatCallback_WrapError(t *testing.T) {
var errSomething = errors.New("something error")

DefineStringFormatCallback("foobar", func(value string) error {
return errSomething
})

s := &Schema{Format: "foobar"}
err := s.VisitJSONString("blablabla")

assert.ErrorIs(t, err, errSomething)

delete(SchemaStringFormats, "foobar")
}

0 comments on commit 0d3c179

Please sign in to comment.