diff --git a/jsonschema/json_pointer.go b/jsonschema/json_pointer.go index 90b4a2c..d7eb4a9 100644 --- a/jsonschema/json_pointer.go +++ b/jsonschema/json_pointer.go @@ -69,11 +69,7 @@ func parseJSONPointer(ptr string) (segments []string, err error) { // This implementation suffices for JSON Schema: pointers are applied only to Schemas, // and refer only to Schemas. func dereferenceJSONPointer(s *Schema, sptr string) (_ *Schema, err error) { - defer func() { - if err != nil { - err = fmt.Errorf("JSON Pointer %q: %w", sptr, err) - } - }() + defer wrapf(&err, "JSON Pointer %q", sptr) segments, err := parseJSONPointer(sptr) if err != nil { diff --git a/jsonschema/util.go b/jsonschema/util.go index 96b32dc..fcb632f 100644 --- a/jsonschema/util.go +++ b/jsonschema/util.go @@ -282,3 +282,10 @@ func assert(cond bool, msg string) { panic("assertion failed: " + msg) } } + +// wrapf wraps *errp with the given formatted message if *errp is not nil. +func wrapf(errp *error, format string, args ...any) { + if *errp != nil { + *errp = fmt.Errorf("%s: %w", fmt.Sprintf(format, args...), *errp) + } +} diff --git a/jsonschema/validate.go b/jsonschema/validate.go index 634417d..12a6242 100644 --- a/jsonschema/validate.go +++ b/jsonschema/validate.go @@ -42,11 +42,7 @@ type state struct { // validate validates the reflected value of the instance. func (st *state) validate(instance reflect.Value, schema *Schema, callerAnns *annotations) (err error) { - defer func() { - if err != nil { - err = fmt.Errorf("%s: %w", schema, err) - } - }() + defer wrapf(&err, "validating %s", schema) st.stack = append(st.stack, schema) // push defer func() {