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>
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)
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{
time.Minute,
testTime,
jsonMarshaler{"xyz"},
+ jsonMarshalerError{jsonMarshaler{"pqr"}},
} {
got := jsonValueString(t, AnyValue(value))
want, err := marshalJSON(value)