Skip to content

Commit 3f197a2

Browse files
jbaeric
authored andcommitted
src/log/slog: JSONHandler checks if error implements json.Marshaler
json.Marshal doesn't do what one might hope on many Go error values. Errors created with errors.New marshal as "{}". So JSONHandler treats errors specially, calling the Error method instead of json.Marshal. However, if the error happens to implement json.Marshaler, then JSONHandler should call json.Marshal after all. This CL makes that change. Change-Id: I2154246b2ca8fa13d4f6f1256f7a16aa98a8c24a Reviewed-on: https://go-review.googlesource.com/c/go/+/480155 Run-TryBot: Jonathan Amsterdam <[email protected]> TryBot-Result: Gopher Robot <[email protected]> Reviewed-by: Alan Donovan <[email protected]>
1 parent 8be4adf commit 3f197a2

File tree

2 files changed

+9
-1
lines changed

2 files changed

+9
-1
lines changed

src/log/slog/json_handler.go

+2-1
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,8 @@ func appendJSONValue(s *handleState, v Value) error {
135135
s.appendTime(v.Time())
136136
case KindAny:
137137
a := v.Any()
138-
if err, ok := a.(error); ok {
138+
_, jm := a.(json.Marshaler)
139+
if err, ok := a.(error); ok && !jm {
139140
s.appendString(err.Error())
140141
} else {
141142
return appendJSONMarshal(s.buf, a)

src/log/slog/json_handler_test.go

+7
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,12 @@ func (j jsonMarshaler) MarshalJSON() ([]byte, error) {
6767
return []byte(fmt.Sprintf(`[%q]`, j.s)), nil
6868
}
6969

70+
type jsonMarshalerError struct {
71+
jsonMarshaler
72+
}
73+
74+
func (jsonMarshalerError) Error() string { return "oops" }
75+
7076
func TestAppendJSONValue(t *testing.T) {
7177
// On most values, jsonAppendAttrValue should agree with json.Marshal.
7278
for _, value := range []any{
@@ -82,6 +88,7 @@ func TestAppendJSONValue(t *testing.T) {
8288
time.Minute,
8389
testTime,
8490
jsonMarshaler{"xyz"},
91+
jsonMarshalerError{jsonMarshaler{"pqr"}},
8592
} {
8693
got := jsonValueString(t, AnyValue(value))
8794
want, err := marshalJSON(value)

0 commit comments

Comments
 (0)