Skip to content

Commit

Permalink
thriftbp: Support native slog.LogValuer implementation for errors
Browse files Browse the repository at this point in the history
The next thrift release, 0.20.0, will add slog.LogValuer for all thrift
generated errors [1] [2]. This prepares us so that WrapBaseplateError
will keep the implementation if it's available to be used with slog.

This also drops support to go 1.20. 1.22 is already at rc2 today so I
think it's time to do that.

[1]: apache/thrift#2884
[2]: https://issues.apache.org/jira/browse/THRIFT-5745
  • Loading branch information
fishy committed Feb 7, 2024
1 parent 10874c7 commit b6e4268
Showing 1 changed file with 24 additions and 8 deletions.
32 changes: 24 additions & 8 deletions internal/thriftint/baseplate_error.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package thriftint
import (
"errors"
"fmt"
"log/slog"
"strings"

"github.com/apache/thrift/lib/go/thrift"
Expand Down Expand Up @@ -36,10 +37,15 @@ var (
)

type wrappedBaseplateError struct {
cause error
bpErr baseplateError
cause error
bpErr baseplateError
logValue slog.Value
}

var (
_ slog.LogValuer = wrappedBaseplateError{}
)

func (e wrappedBaseplateError) Error() string {
var sb strings.Builder
sb.WriteString(fmt.Sprintf("baseplate.Error: %q", e.bpErr.GetMessage()))
Expand All @@ -61,6 +67,10 @@ func (e wrappedBaseplateError) Error() string {
return sb.String()
}

func (e wrappedBaseplateError) LogValue() slog.Value {
return e.logValue
}

func (e wrappedBaseplateError) Unwrap() error {
return e.cause
}
Expand All @@ -83,11 +93,17 @@ func WrapBaseplateError(e error) error {
}

var bpErr baseplateError
if errors.As(e, &bpErr) {
return wrappedBaseplateError{
cause: e,
bpErr: bpErr,
}
if !errors.As(e, &bpErr) {
return e
}
wrapped := wrappedBaseplateError{
cause: e,
bpErr: bpErr,
}
if v, ok := e.(slog.LogValuer); ok {
wrapped.logValue = v.LogValue()
} else {
wrapped.logValue = slog.StringValue(wrapped.Error())
}
return e
return wrapped
}

0 comments on commit b6e4268

Please sign in to comment.