| 1 |
// Package errors provides error handling utilities. |
| 2 |
package errors |
| 3 |
|
| 4 |
import "strings" |
| 5 |
|
| 6 |
// Join returns an error that wraps the given errors. |
| 7 |
// Any nil error values are discarded. |
| 8 |
// Join returns nil if every value in errs is nil. |
| 9 |
// The error formats as the concatenation of the strings obtained |
| 10 |
// by calling the Error method of each element of errs, with a newline |
| 11 |
// between each string. |
| 12 |
// |
| 13 |
// A non-nil error returned by Join implements the Unwrap() []error method. |
| 14 |
// |
| 15 |
// This is copied from Go 1.20 errors.Unwrap, with some tuning to avoid using unsafe. |
| 16 |
// The main goal is to have this available in older Go versions. |
| 17 |
func Join(errs ...error) error { |
| 18 |
var nonNil []error //nolint:prealloc |
| 19 |
for _, err := range errs { |
| 20 |
if err == nil { |
| 21 |
continue |
| 22 |
} |
| 23 |
nonNil = append(nonNil, err) |
| 24 |
} |
| 25 |
if len(nonNil) == 0 { |
| 26 |
return nil |
| 27 |
} |
| 28 |
return &joinError{ |
| 29 |
errs: nonNil, |
| 30 |
} |
| 31 |
} |
| 32 |
|
| 33 |
type joinError struct { |
| 34 |
errs []error |
| 35 |
} |
| 36 |
|
| 37 |
func (e *joinError) Error() string { |
| 38 |
strs := make([]string, 0, len(e.errs)) |
| 39 |
for _, err := range e.errs { |
| 40 |
strs = append(strs, err.Error()) |
| 41 |
} |
| 42 |
return strings.Join(strs, "\n") |
| 43 |
} |
| 44 |
|
| 45 |
func (e *joinError) Unwrap() []error { |
| 46 |
return e.errs |
| 47 |
} |