From 4e9d520c2e46a1fcc54077bc41c4c4dd7cbd8d23 Mon Sep 17 00:00:00 2001 From: Jonathan Amsterdam Date: Tue, 27 May 2025 07:32:06 -0400 Subject: [PATCH] internal/mcp/jsonschema: generalize error wrapping Add a wrapf function to simplify defers that wrap errors. Change-Id: If4bedec7d3f56f609d3ca4620aebe7637a59f6bf Reviewed-on: https://go-review.googlesource.com/c/tools/+/676475 LUCI-TryBot-Result: Go LUCI Reviewed-by: Alan Donovan --- jsonschema/json_pointer.go | 6 +----- jsonschema/util.go | 7 +++++++ jsonschema/validate.go | 6 +----- 3 files changed, 9 insertions(+), 10 deletions(-) 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() {