diff --git a/README.md b/README.md index 0bf92aa..2eacbbc 100644 --- a/README.md +++ b/README.md @@ -123,26 +123,23 @@ v, err := encoder.Encode(m, encoder.SortMapKeys) ### Print Syntax Error ```go +import "github.com/bytedance/sonic" import "github.com/bytedance/sonic/decoder" var data interface{} -dc := decoder.NewDecoder("[[[}]]") -if err := dc.Decode(&data); err != nil { +err := sonic.Unmarshal("[[[}]]", &data) +if err != nil { + /*one line by default*/ + println(e.Error())) // "Syntax error at index 3: invalid char\n\n\t[[[}]]\n\t...^..\n" + /*pretty print*/ if e, ok := err.(decoder.SyntaxError); ok { - /*Syntax error at index 3: invalid char [[[}]] ...^.. */ print(e.Description()) - - /*"Syntax error at index 3: invalid char\n\n\t[[[}]]\n\t...^..\n"*/ - println(fmt.Sprintf("%q", e.Description())) } - - /*Decode: Syntax error at index 3: invalid char*/ - t.Fatalf("Decode: %v", err) } ``` diff --git a/decoder/errors.go b/decoder/errors.go index 5276035..c9272a2 100644 --- a/decoder/errors.go +++ b/decoder/errors.go @@ -35,7 +35,7 @@ type SyntaxError struct { } func (self SyntaxError) Error() string { - return fmt.Sprintf("Syntax error at index %d: %s", self.Pos, self.Code.Message()) + return fmt.Sprintf("%q", self.Description()) } func (self SyntaxError) Description() string { @@ -45,7 +45,7 @@ func (self SyntaxError) Description() string { /* check for empty source */ if self.Src == "" { - return self.Error() + " (no sources available)" + return fmt.Sprintf("no sources available: %#v", self) } /* prevent slicing before the beginning */ @@ -71,8 +71,9 @@ func (self SyntaxError) Description() string { /* compose the error description */ return fmt.Sprintf( - "%s\n\n\t%s\n\t%s^%s\n", - self.Error(), + "Syntax error at index %d: %s\n\n\t%s\n\t%s^%s\n", + self.Pos, + self.Code.Message(), self.Src[p:q], strings.Repeat(".", x), strings.Repeat(".", y), diff --git a/decoder/errors_test.go b/decoder/errors_test.go index 5ab4bed..144ad3c 100644 --- a/decoder/errors_test.go +++ b/decoder/errors_test.go @@ -21,6 +21,7 @@ import ( `testing` `github.com/bytedance/sonic/internal/native/types` + `github.com/stretchr/testify/assert` ) func make_err(src string, pos int) SyntaxError { @@ -48,7 +49,10 @@ func TestErrors_AfterRightEdge(t *testing.T) { } func TestErrors_ShortDescription(t *testing.T) { - println(make_err("hello, world", 5).Description()) + e := make_err("hello, world", 5) + println(e.Description()) + assert.Equal(t, "Syntax error at index 5: invalid char\n\n\thello, world\n\t.....^......\n", e.Description()) + assert.Equal(t, `"Syntax error at index 5: invalid char\n\n\thello, world\n\t.....^......\n"`, e.Error()) } func TestErrors_EmptyDescription(t *testing.T) { @@ -61,7 +65,7 @@ func TestDecoderErrorStackOverflower(t *testing.T) { for i:=0; i