Skip to content

schema.markSchemaErrorKey() disposes of oneOf context #940

@jordan-wu-97

Description

@jordan-wu-97

oneOf validation provides a good reason of value doesn't match any schema from "oneOf"

kin-openapi/openapi3/schema.go

Lines 1380 to 1381 in 9dbb4c3

e.Origin = fmt.Errorf("doesn't match schema due to: %w", validationErrors)
e.Reason = `value doesn't match any schema from "oneOf"`

However, the function markSchemaErrorKey unwraps the Origin to err, resulting in the original error containing the oneOf context being lost (line 2125)

kin-openapi/openapi3/schema.go

Lines 2121 to 2139 in 9dbb4c3

func markSchemaErrorKey(err error, key string) error {
var me multiErrorForOneOf
if errors.As(err, &me) {
err = me.Unwrap()
}
if v, ok := err.(*SchemaError); ok {
v.reversePath = append(v.reversePath, key)
return v
}
if v, ok := err.(MultiError); ok {
for _, e := range v {
_ = markSchemaErrorKey(e, key)
}
return v
}
return err
}

Example:

func TestOneOfSchema(t *testing.T) {

	openapi3.SchemaErrorDetailsDisabled = true

	// language=json
	raw := `
{
	"foo": [ "bar" ]
}
`

	// language=json
	schema := `
{
	"type": "object",
	"properties": {
		"foo": {
			"oneOf": [
				{
					"type": "number"
				},
					{
					"type": "string"
				}
			]
		}
	}
}
`

	s := openapi3.NewSchema()
	err := s.UnmarshalJSON([]byte(schema))
	require.NoError(t, err)
	err = s.Validate(context.Background())
	require.NoError(t, err)

	obj := make(map[string]interface{})
	err = json.Unmarshal([]byte(raw), &obj)
	require.NoError(t, err)

	err = s.VisitJSON(obj, openapi3.MultiErrors())
	fmt.Println(err.Error())

}

Output:

Error at "/foo": value must be a number | Error at "/foo": value must be a string

We lost the error message describing that foo must be oneOf the schemas

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions