Repository navigation
feat: support %w verb in Errorf for error wrapping - #254
AdamMagued wants to merge 2 commits into
Conversation
Signed-off-by: AdamMagued <adamismailmageud@gmail.com>
|
Why not just make fundamental implement Unwrap? |
|
There are a couple of architectural considerations around
That said, if you prefer to keep pkg/errors focused strictly on single-error wrapping and would rather unify single-wrap |
| err := fmt.Errorf(format, args...) | ||
| if u, ok := err.(interface{ Unwrap() error }); ok { | ||
| return &wrapError{ | ||
| msg: err.Error(), | ||
| err: u.Unwrap(), | ||
| stack: callers(), | ||
| } | ||
| } | ||
| if u, ok := err.(interface{ Unwrap() []error }); ok { | ||
| return &wrapErrors{ | ||
| msg: err.Error(), | ||
| errs: u.Unwrap(), | ||
| stack: callers(), | ||
| } | ||
| } |
There was a problem hiding this comment.
😐 A type switch would make more sense here.
There was a problem hiding this comment.
Updated in eae2cc5: replaced the separate type assertions with switch u := err.(type)
| type wrapError struct { | ||
| msg string | ||
| err error | ||
| *stack | ||
| } |
There was a problem hiding this comment.
Why recreate &withMessage{ cause: &fundamental{ … } }?
There was a problem hiding this comment.
Updated in eae2cc5: wrapError now embeds *fundamental to reuse Error(), Format(), and StackTrace() without duplicating them. withMessage.Error() prepends w.msg + ": ", which alters fmt.Errorf formatting when %w appears mid-string or alone
| if u, ok := err.(interface{ Unwrap() error }); ok { | ||
| return &wrapError{ | ||
| msg: err.Error(), | ||
| err: u.Unwrap(), |
There was a problem hiding this comment.
We should probably check to make sure that u.Unwrap is non-nil… otherwise, we should just return a fundamental.
There was a problem hiding this comment.
Updated in eae2cc5: Errorf now checks u.Unwrap() != nil and returns *fundamental when nil
| if u, ok := err.(interface{ Unwrap() []error }); ok { | ||
| return &wrapErrors{ | ||
| msg: err.Error(), | ||
| errs: u.Unwrap(), |
There was a problem hiding this comment.
Similarly, if this returns a length 1 unwrap, we could just return a wrapError and a length 0 unwrap, we could just return a fundamental.
There was a problem hiding this comment.
Updated in eae2cc5: 0-length slices (and 1-length with nil) return *fundamental, and 1-length non-nil returns *wrapError
|
|
||
| type wrapErrors struct { | ||
| msg string | ||
| errs []error |
There was a problem hiding this comment.
Why recreate &withMessage{ cause: errors.Join( &fundamental { … }, … ) }?
There was a problem hiding this comment.
Updated in eae2cc5: wrapErrors now embeds *fundamental as well. errors.Join requires Go 1.20+ (this package targets Go 1.13+) and joins messages with newlines rather than preserving fmt.Errorf formatting
…ndamental Signed-off-by: AdamMagued <adamismailmageud@gmail.com>
Fixes #244
Solution
Verified with container sandbox test suite.