Add JsonSprintError
This commit is contained in:
15
json.go
15
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.
|
||||
|
||||
27
json_test.go
27
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")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user