Add JsonSprintError
This commit is contained in:
13
json.go
13
json.go
@@ -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))
|
||||||
|
|
||||||
@@ -17,12 +17,19 @@ func JsonPrintError(err error, content []byte) {
|
|||||||
|
|
||||||
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.
|
||||||
func JsonEqual(a, b string) bool {
|
func JsonEqual(a, b string) bool {
|
||||||
var o1 any
|
var o1 any
|
||||||
|
|||||||
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