Documentation
¶
Index ¶
Examples ¶
Constants ¶
const FieldNamePanicMessage = "panic"
const FieldNamePanicStackTrace = "stack"
Variables ¶
This section is empty.
Functions ¶
func Collect ¶
Collect finds aggregates all errors that match the given target type, within the error chain of err. The resulting slice contains target error instances in reverse order.
func DefaultErrorGenerator ¶
Types ¶
type BaseError ¶
type BaseError[T any] struct { // contains filtered or unexported fields }
func NewBaseError ¶
func (*BaseError[T]) ContextFields ¶
func (e *BaseError[T]) ContextFields() T
func (*BaseError[T]) MarkAsPanic ¶
func (*BaseError[T]) SetContextFields ¶
func (e *BaseError[T]) SetContextFields(f T)
SetContextFields is a setter that replaces the attached error context.
type ErrorGenerator ¶
type Recoverer ¶
type Recoverer[T error] struct { PanicValueTransform func(r any) (string, error) NewErrorFunc ErrorGenerator[T] }
Example ¶
package main
import (
"fmt"
"go.uber.org/zap"
"golang.org/x/sync/errgroup"
"github.com/georgepsarakis/errorcontext"
zaperrorcontext "github.com/georgepsarakis/errorcontext/backend/zap"
)
func main() {
cfg := zap.NewProductionConfig()
zapLogger, err := cfg.Build()
if err != nil {
panic(err)
}
grp := errgroup.Group{}
recoverer := errorcontext.Recoverer[*zaperrorcontext.Error]{
NewErrorFunc: func(p errorcontext.Panic) *zaperrorcontext.Error {
return zaperrorcontext.FromPanic(p)
},
}
grp.Go(recoverer.WrapFunc(func() error {
panic("something bad happened")
}))
grp.Go(func() error {
fmt.Println("Hello World")
return nil
})
if err := grp.Wait(); err != nil {
zapLogger.Warn("something failed",
zap.Dict("error_context", zaperrorcontext.AsContext(err)...),
zap.Error(err))
}
}
Output: Hello World
func NewRecoverer ¶
func NewRecoverer[T error](newError ErrorGenerator[T]) Recoverer[T]
func (Recoverer[T]) Format ¶
Format transforms an arbitrary value thrown by panic to an error message along with providing the current goroutine stack trace for the panic root cause. If PanicValueTransform is non-nil, an attempt to format the recovered value is performed. If the formatter function returns an error, a fallback approach is used and the failure error message is appended to the standard message template. Note: this method is intended to be public in order to facilitate testing.
func (Recoverer[T]) Wrap ¶
Wrap allows recovery from panics for the given function. Panics are translated and propagated as errors that can be handled accordingly. Note: unrecovered panics can cause an abnormal program exit.
func (Recoverer[T]) WrapFunc ¶
WrapFunc is a convenience wrapper that returns a decorated function, ensuring that panics are converted to error values.
A common use case is to pass the function directly to errgroup.Submit:
grp := errgroup.Group{}
recoverer := errorcontext.Recoverer[error]{
NewErrorFunc: errorcontext.DefaultErrorGenerator,
}
grp.Go(recoverer.WrapFunc(func() error {
panic("something bad happened")
}))