Skip to content

Commit

Permalink
help with json errors
Browse files Browse the repository at this point in the history
Signed-off-by: Doug Davis <[email protected]>
  • Loading branch information
duglin committed Jan 5, 2025
1 parent fee4b64 commit 6e65d14
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 5 deletions.
25 changes: 25 additions & 0 deletions registry/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,27 @@ func Unmarshal(buf []byte, v any) error {
dec := json.NewDecoder(bytes.NewReader(buf))
dec.DisallowUnknownFields()
if err := dec.Decode(v); err != nil {
// Try to grab the json around the error
offset := int(dec.InputOffset())
nearStart := offset - 200
if nearStart < 0 {
nearStart = 0
}
nearEnd := offset + 200
if nearEnd >= len(buf) {
nearEnd = len(buf)
}
near := ""
if nearStart != offset {
if nearStart != 0 {
near = ".s."
}
near = string(buf[nearStart:nearEnd])
}
if offset > 0 && nearEnd != offset {
near += ".e."
}

msg := err.Error()

if jerr, ok := err.(*json.UnmarshalTypeError); ok {
Expand All @@ -384,6 +405,10 @@ func Unmarshal(buf []byte, v any) error {
}
}
msg, _ = strings.CutPrefix(msg, "json: ")
if near != "" {
msg += " near: " + near
}

return errors.New(msg)
}
return nil
Expand Down
9 changes: 6 additions & 3 deletions tests/capabilities_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ func TestCapabilitySimple(t *testing.T) {
{
Name: "extra key",
Cap: `{"pagination": true, "bad": true}`,
Exp: `Unknown capability: "bad"`,
Exp: `Unknown capability: "bad" near: {"pagination": true, "bad": true}`,
},
}

Expand Down Expand Up @@ -557,7 +557,7 @@ func TestCapabilityPath(t *testing.T) {

// Unknown key
xHTTP(t, reg, "PUT", "/capabilities", `{ "foo": [] }`,
400, "Unknown capability: \"foo\"\n")
400, "Unknown capability: \"foo\" near: { \"foo\": [] }\n")
}

func TestCapabilityAttr(t *testing.T) {
Expand Down Expand Up @@ -765,7 +765,10 @@ func TestCapabilityAttr(t *testing.T) {
// Unknown key
xHTTP(t, reg, "PUT", "/?inline=capabilities", `{ "capabilities":
{"foo": [] }}`,
400, "Unknown capability: \"foo\"\n")
400, `Unknown capability: "foo" near: {
"foo": []
}
`)

}

Expand Down
4 changes: 2 additions & 2 deletions tests/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -261,13 +261,13 @@ func xCheckEqual(t *testing.T, extra string, gotAny any, expAny any) {
}

if pos == len(got) {
t.Fatalf("%s"+
t.Fatalf("%s\n"+
"Expected:\n%s\nGot:\n%s\nGot ended early at(%d)[%02X]:\n%q",
extra, exp, got, pos, exp[pos], got[pos:])
}

if pos == len(exp) {
t.Fatalf("%s"+
t.Fatalf("%s\n"+
"Expected:\n%s\nGot:\n%s\nExp ended early at(%d)[%02X]:\n%q",
extra, exp, got, pos, got[pos], got[pos:])
}
Expand Down

0 comments on commit 6e65d14

Please sign in to comment.