From b6e426832f58b6c6b4af37cb1571e051126d8f97 Mon Sep 17 00:00:00 2001 From: Yuxuan 'fishy' Wang Date: Wed, 24 Jan 2024 09:46:56 -0800 Subject: [PATCH] thriftbp: Support native slog.LogValuer implementation for errors 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]: https://github.com/apache/thrift/pull/2884 [2]: https://issues.apache.org/jira/browse/THRIFT-5745 --- internal/thriftint/baseplate_error.go | 32 ++++++++++++++++++++------- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/internal/thriftint/baseplate_error.go b/internal/thriftint/baseplate_error.go index ab5d57ce8..f3d61cfd3 100644 --- a/internal/thriftint/baseplate_error.go +++ b/internal/thriftint/baseplate_error.go @@ -5,6 +5,7 @@ package thriftint import ( "errors" "fmt" + "log/slog" "strings" "github.com/apache/thrift/lib/go/thrift" @@ -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())) @@ -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 } @@ -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 }