]> Cypherpunks repositories - gostls13.git/commitdiff
src/log/slog: JSONHandler checks if error implements json.Marshaler
authorJonathan Amsterdam <jba@google.com>
Wed, 29 Mar 2023 13:57:33 +0000 (09:57 -0400)
committerJonathan Amsterdam <jba@google.com>
Wed, 29 Mar 2023 20:46:52 +0000 (20:46 +0000)
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 <jba@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Alan Donovan <adonovan@google.com>
src/log/slog/json_handler.go
src/log/slog/json_handler_test.go

index 96545d58d66af6acffd97d46201fa1f1ea3a6440..ce249acfd399abcc9cc3da6d58530a7f3b1ef41f 100644 (file)
@@ -135,7 +135,8 @@ func appendJSONValue(s *handleState, v Value) error {
                s.appendTime(v.Time())
        case KindAny:
                a := v.Any()
-               if err, ok := a.(error); ok {
+               _, jm := a.(json.Marshaler)
+               if err, ok := a.(error); ok && !jm {
                        s.appendString(err.Error())
                } else {
                        return appendJSONMarshal(s.buf, a)
index 0a38969f46a0cda8eef7b03a1c58837592a3caf0..7c683f0d34da0599349ffced1b13037d5f8d5614 100644 (file)
@@ -67,6 +67,12 @@ func (j jsonMarshaler) MarshalJSON() ([]byte, error) {
        return []byte(fmt.Sprintf(`[%q]`, j.s)), nil
 }
 
+type jsonMarshalerError struct {
+       jsonMarshaler
+}
+
+func (jsonMarshalerError) Error() string { return "oops" }
+
 func TestAppendJSONValue(t *testing.T) {
        // On most values, jsonAppendAttrValue should agree with json.Marshal.
        for _, value := range []any{
@@ -82,6 +88,7 @@ func TestAppendJSONValue(t *testing.T) {
                time.Minute,
                testTime,
                jsonMarshaler{"xyz"},
+               jsonMarshalerError{jsonMarshaler{"pqr"}},
        } {
                got := jsonValueString(t, AnyValue(value))
                want, err := marshalJSON(value)