Add JsonSprintError

This commit is contained in:
George Suntres
2026-04-16 10:16:03 -04:00
parent 706ed2e6b0
commit 7a6c5b6c3c
2 changed files with 38 additions and 4 deletions

15
json.go
View File

@@ -6,7 +6,7 @@ import (
"encoding/json" "encoding/json"
) )
func JsonPrintError(err error, content []byte) { func JsonSprintError(err error, content []byte) (error, string) {
if syntaxErr, ok := err.(*json.SyntaxError); ok { if syntaxErr, ok := err.(*json.SyntaxError); ok {
totalLen := int64(len(content)) totalLen := int64(len(content))
@@ -16,11 +16,18 @@ func JsonPrintError(err error, content []byte) {
to := MathMin(syntaxErr.Offset + min, totalLen) to := MathMin(syntaxErr.Offset + min, totalLen)
sliceBuf := content[from:to] sliceBuf := content[from:to]
log.Printf("Failed to unmarshal %#v \n %s", syntaxErr, string(sliceBuf)) return err, string(sliceBuf)
} else { } else {
log.Printf("%v", err)
return err, ""
} }
}
func JsonPrintError(err error, content []byte) {
e, s := JsonSprintError(err, content)
log.Printf("Failed to unmarshal %#v \n %s", e, s)
} }
// JsonEqual check if two json string representations are equal. // JsonEqual check if two json string representations are equal.

View File

@@ -39,3 +39,30 @@ func TestJsonPrintError(t *testing.T) {
} }
} }
func TestJsonSprintError(t *testing.T) {
jsonstr := `
{
"name": "George",
"age": 87,
active": "false",
"properties": {
"one": "two",
"three": "four"
}
}
`
var buf bytes.Buffer
log.SetOutput(&buf)
content := []byte(jsonstr)
var data map[string]any
err := json.Unmarshal(content, &data)
_, s := JsonSprintError(err, content)
if s == "" {
t.Fatal("should have printed the error")
}
}