diff --git a/openapi3/schema.go b/openapi3/schema.go index e5cded877..1d77e816a 100644 --- a/openapi3/schema.go +++ b/openapi3/schema.go @@ -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 diff --git a/openapi3/schema_formats_test.go b/openapi3/schema_formats_test.go index 5cceb8cf0..eeb7894a7 100644 --- a/openapi3/schema_formats_test.go +++ b/openapi3/schema_formats_test.go @@ -2,8 +2,10 @@ package openapi3 import ( "context" + "errors" "testing" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -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") +}