From 7a6c5b6c3c8cb06fa476f30eca28b6f8c229ff3c Mon Sep 17 00:00:00 2001 From: George Suntres Date: Thu, 16 Apr 2026 10:16:03 -0400 Subject: [PATCH] Add JsonSprintError --- json.go | 15 +++++++++++---- json_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/json.go b/json.go index 946a5b4..4f184f7 100644 --- a/json.go +++ b/json.go @@ -6,7 +6,7 @@ import ( "encoding/json" ) -func JsonPrintError(err error, content []byte) { +func JsonSprintError(err error, content []byte) (error, string) { if syntaxErr, ok := err.(*json.SyntaxError); ok { totalLen := int64(len(content)) @@ -16,11 +16,18 @@ func JsonPrintError(err error, content []byte) { to := MathMin(syntaxErr.Offset + min, totalLen) sliceBuf := content[from:to] - - log.Printf("Failed to unmarshal %#v \n %s", syntaxErr, string(sliceBuf)) + + return err, string(sliceBuf) } 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. diff --git a/json_test.go b/json_test.go index ec1b3bf..ed9377d 100644 --- a/json_test.go +++ b/json_test.go @@ -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") + } +} \ No newline at end of file