github.com/bingoohuang/gg@v0.0.0-20240325092523-45da7dee9335/pkg/jsoni/error_test.go (about) 1 package jsoni 2 3 import ( 4 "context" 5 "encoding/json" 6 "errors" 7 "strconv" 8 "testing" 9 "unsafe" 10 11 "github.com/modern-go/reflect2" 12 "github.com/stretchr/testify/assert" 13 ) 14 15 type JSONError struct { 16 Error error 17 } 18 19 func (e JSONError) MarshalJSON() ([]byte, error) { 20 return json.Marshal(e.Error.Error()) 21 } 22 23 type errorEncoder struct{} 24 25 func (e errorEncoder) IsEmpty(ctx context.Context, ptr unsafe.Pointer, checkZero bool) bool { 26 err := *((*error)(ptr)) 27 return err == nil 28 } 29 30 func (e errorEncoder) Encode(ctx context.Context, ptr unsafe.Pointer, stream *Stream) { 31 s := *((*error)(ptr)) 32 q := strconv.Quote(s.Error()) 33 stream.WriteRaw(q) 34 } 35 36 type A struct { 37 Err JSONError `json:"err"` 38 } 39 40 type B struct { 41 Err error `json:"err"` 42 } 43 44 func TestError(t *testing.T) { 45 j, _ := json.Marshal(A{Err: JSONError{errors.New("err")}}) 46 assert.Equal(t, `{"err":"err"}`, string(j)) 47 48 jc := Config{ 49 EscapeHTML: true, 50 }.Froze() 51 jc.RegisterTypeEncoder(reflect2.TypeOfPtr((*error)(nil)).Elem().String(), &errorEncoder{}) 52 53 j, _ = jc.Marshal(context.TODO(), B{Err: errors.New("err")}) 54 assert.Equal(t, `{"err":"err"}`, string(j)) 55 }