From 30e9393f394a7bbcc073b4ecf8228529de22a291 Mon Sep 17 00:00:00 2001 From: Martin Wohlfart Date: Thu, 19 Dec 2024 01:01:42 +0100 Subject: [PATCH] Add WithBuilder and FromContext (#38) --- context.go | 17 +++++++++++++++++ oops.go | 9 +++++++++ oops_test.go | 14 ++++++++++++++ 3 files changed, 40 insertions(+) create mode 100644 context.go diff --git a/context.go b/context.go new file mode 100644 index 0000000..c5b53a5 --- /dev/null +++ b/context.go @@ -0,0 +1,17 @@ +package oops + +import "context" + +type contextKey string + +const contextKeyOops = contextKey("oops") + +func getBuilderFromContext(ctx context.Context) (OopsErrorBuilder, bool) { + b, ok := ctx.Value(contextKeyOops).(OopsErrorBuilder) + return b, ok +} + +// WithBuilder set the error builder in the context, to be retrieved later with FromContext. +func WithBuilder(ctx context.Context, builder OopsErrorBuilder) context.Context { + return context.WithValue(ctx, contextKeyOops, builder) +} diff --git a/oops.go b/oops.go index d65e4e6..e60c066 100644 --- a/oops.go +++ b/oops.go @@ -30,6 +30,15 @@ func Errorf(format string, args ...any) error { return new().Errorf(format, args...) } +func FromContext(ctx context.Context) OopsErrorBuilder { + builder, ok := getBuilderFromContext(ctx) + if !ok { + new() + } + + return builder +} + func Join(e ...error) error { return new().Join(e...) } diff --git a/oops_test.go b/oops_test.go index 870dd1d..df9ce54 100644 --- a/oops_test.go +++ b/oops_test.go @@ -41,6 +41,20 @@ func TestOopsWrapf(t *testing.T) { is.Nil(err) } +func TestOopsFromContext(t *testing.T) { + is := assert.New(t) + + domain := "domain" + key, val := "foo", "bar" + builder := new().In(domain).With(key, val).WithContext(context.Background()) + ctx := WithBuilder(context.Background(), builder) + + err := FromContext(ctx).Errorf("a message %d", 42) + is.Error(err) + is.Equal(domain, err.(OopsError).domain) + is.Equal(val, err.(OopsError).context[key]) +} + func TestOopsErrorf(t *testing.T) { is := assert.New(t)