Skip to content

Commit

Permalink
Add WithBuilder and FromContext (#38)
Browse files Browse the repository at this point in the history
  • Loading branch information
mbark authored Dec 19, 2024
1 parent cc2f91a commit 30e9393
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
17 changes: 17 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
@@ -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)
}
9 changes: 9 additions & 0 deletions oops.go
Original file line number Diff line number Diff line change
Expand Up @@ -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...)
}
Expand Down
14 changes: 14 additions & 0 deletions oops_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down

0 comments on commit 30e9393

Please sign in to comment.