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 attach and mask functions for joining errors in a different way #16

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
42 changes: 42 additions & 0 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -409,3 +409,45 @@ func (c customMessage) As(target any) bool {
func (c customMessage) Error() string {
return c.msg
}

// Attach will join the extra errors to the base error where
// only the base error is part of the message but all errors
// are wrapped at the same level.
func Attach(base error, extra ...error) error {
if len(extra) == 0 {
return base
}

return &attachedError{
error: base,
wrapped: append([]error{base}, extra...),
}
}

// Mask will join the extra errors where the base error is
// part of the message but the extra errors are joined earlier
// in the chain and would mask the base error when used with
// errors.Is or errors.As.
func Mask(base error, extra ...error) error {
if len(extra) == 0 {
return base
}

return &attachedError{
error: base,
wrapped: append(extra, base),
}
}

// attachedError is used to attach errors to a base
// error. The attached errors will be hidden from view when
// being printed but will show up when errors.Is or errors.As
// are used.
type attachedError struct {
error
wrapped []error
}

func (e *attachedError) Unwrap() []error {
return e.wrapped
}
Loading