Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle errors printing like slog json marshaller #60

Merged
merged 3 commits into from
Apr 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 16 additions & 5 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -637,11 +637,8 @@ func toJSON(v any) string {
return strconv.Quote(fmt.Sprintf("ERR marshaling %v: %v", v, err))
}
str := string(bytes)
// This is kinda hacky way to handle both structured and custom serialization errors, and
// struct with no public fields for which we need to call Error() to get a useful string.
if e, isError := v.(error); isError && str == "{}" {
return fmt.Sprintf("%q", e.Error())
}
// We now handle errors before calling toJSON: if there is a marshaller we use it
// otherwise we use the string from .Error()
return str
}

Expand All @@ -653,6 +650,20 @@ func (v ValueType[T]) String() string {
return fmt.Sprint(s)
case string:
return fmt.Sprintf("%q", s)
case error:
// Sadly structured errors like nettwork error don't have the reason in
// the exposed struct/JSON - ie on gets
// {"Op":"read","Net":"tcp","Source":{"IP":"127.0.0.1","Port":60067,"Zone":""},
// "Addr":{"IP":"127.0.0.1","Port":3000,"Zone":""},"Err":{}}
// instead of
// read tcp 127.0.0.1:60067->127.0.0.1:3000: i/o timeout
// Noticed in https://github.com/fortio/fortio/issues/913
_, hasMarshaller := s.(json.Marshaler)
if hasMarshaller {
return toJSON(v.Val)
} else {
return fmt.Sprintf("%q", s.Error())
}
/* It's all handled by json fallback now even though slightly more expensive at runtime, it's a lot simpler */
default:
return toJSON(v.Val) // was fmt.Sprintf("%q", fmt.Sprint(v.Val))
Expand Down
6 changes: 6 additions & 0 deletions logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -757,10 +757,16 @@ type customError struct {
Code int
}

type customErrorAlias customError

func (e customError) Error() string {
return fmt.Sprintf("custom error %s (code %d)", e.Msg, e.Code)
}

func (e customError) MarshalJSON() ([]byte, error) {
return json.Marshal(customErrorAlias(e))
}

func TestSerializationOfError(t *testing.T) {
var err error
kv := Any("err", err)
Expand Down
Loading