-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
63 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
package kafka | ||
|
||
import ( | ||
"context" | ||
) | ||
|
||
// Error is an error with an associated [Message] providing additional context. | ||
type Error struct { | ||
Message Message | ||
Err error | ||
} | ||
|
||
// Error returns the original error message without modifications. | ||
func (err Error) Error() string { | ||
return err.Err.Error() | ||
} | ||
|
||
// Unwrap returns the original error. | ||
func (err Error) Unwrap() error { | ||
return err.Err | ||
} | ||
|
||
// Handler is an interface for processing errors. | ||
type ErrorHandler interface { | ||
Handle(ctx context.Context, err error) | ||
} | ||
|
||
// ErrorHandlerFunc is an adapter type that allows the use of ordinary functions as an [ErrorHandler]. | ||
type ErrorHandlerFunc func(ctx context.Context, err error) | ||
|
||
// Handle calls itself passing all arguments through. | ||
func (fn ErrorHandlerFunc) Handle(ctx context.Context, err error) { | ||
fn(ctx, err) | ||
} | ||
|
||
// WrapErrorMiddleware returns a middleware that wraps errors with additional context using the Error type. | ||
func WrapErrorMiddleware() Middleware { | ||
return func(next Handler) Handler { | ||
return HandlerFunc(func(ctx context.Context, msg Message) error { | ||
if err := next.Handle(ctx, msg); err != nil { | ||
return Error{ | ||
Message: msg, | ||
Err: err, | ||
} | ||
} | ||
|
||
return nil | ||
}) | ||
} | ||
} | ||
|
||
// CatchErrorMiddleware returns a middleware that catches and handles errors without propagation. | ||
func CatchErrorMiddleware(eh ErrorHandler) Middleware { | ||
return func(next Handler) Handler { | ||
return HandlerFunc(func(ctx context.Context, msg Message) error { | ||
if err := next.Handle(ctx, msg); err != nil { | ||
eh.Handle(ctx, err) | ||
} | ||
|
||
return nil | ||
}) | ||
} | ||
} |