Skip to content

Commit

Permalink
Add Merge to ierrors
Browse files Browse the repository at this point in the history
  • Loading branch information
muXxer committed Mar 14, 2024
1 parent c066fea commit 8b0b59e
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
23 changes: 23 additions & 0 deletions ierrors/ierrors_no_stacktrace.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,29 @@ func Join(errs ...error) error {
return errors.Join(errs...)
}

// Merge merges multiple errors into a single error by wrapping them.
// Any nil error values are discarded.
// Merge returns nil if every value in errs is nil.
// Merge adds a stacktrace to the error if there was no stacktrace
// in the error tree yet and if the build flag "stacktrace" is set.
func Merge(errs ...error) error {
var result error
for _, err := range errs {
if err == nil {
continue
}

if result == nil {
result = err
continue
}

result = fmt.Errorf("%w: %w", result, err)
}

return result
}

// Errorf formats according to a format specifier and returns the string as a
// value that satisfies error.
//
Expand Down
27 changes: 27 additions & 0 deletions ierrors/ierrors_stacktrace.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@ func newErrorWithStacktrace(err error, stacktrace string) *errorWithStacktrace {
// if yes, it simply returns the err.
// if not, it returns a new error with a stacktrace appended.
func ensureStacktraceUniqueness(err error) error {
if err == nil {
return nil
}

var errWithStacktrace *errorWithStacktrace
if errors.As(err, &errWithStacktrace) {
return err
Expand All @@ -78,6 +82,29 @@ func Join(errs ...error) error {
return ensureStacktraceUniqueness(errors.Join(errs...))
}

// Merge merges multiple errors into a single error by wrapping them.
// Any nil error values are discarded.
// Merge returns nil if every value in errs is nil.
// Merge adds a stacktrace to the error if there was no stacktrace
// in the error tree yet and if the build flag "stacktrace" is set.
func Merge(errs ...error) error {
var result error
for _, err := range errs {
if err == nil {
continue
}

if result == nil {
result = err
continue
}

result = fmt.Errorf("%w: %w", result, err)
}

return ensureStacktraceUniqueness(result)
}

// Errorf formats according to a format specifier and returns the string as a
// value that satisfies error.
//
Expand Down
3 changes: 3 additions & 0 deletions ierrors/ierrors_stacktrace_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,4 +63,7 @@ func TestErrors(t *testing.T) {

err15 := WithStack(errStacktrace)
require.Equal(t, 1, strings.Count(err15.Error(), "github.com/iotaledger/hive.go/ierrors.TestErrors"))

err16 := Merge(New("err16"), New("merged"))
require.Equal(t, 1, strings.Count(err16.Error(), "github.com/iotaledger/hive.go/ierrors.TestErrors"))
}

0 comments on commit 8b0b59e

Please sign in to comment.