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

Add WithBuilder and FromContext functions #38

Merged
merged 1 commit into from
Dec 19, 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
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