multierror.go 818 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package multierror
  2. import (
  3. "strings"
  4. )
  5. // Join is a drop-in replacement for errors.Join with better formatting.
  6. func Join(errs ...error) error {
  7. n := 0
  8. for _, err := range errs {
  9. if err != nil {
  10. n++
  11. }
  12. }
  13. if n == 0 {
  14. return nil
  15. }
  16. e := &joinError{
  17. errs: make([]error, 0, n),
  18. }
  19. for _, err := range errs {
  20. if err != nil {
  21. e.errs = append(e.errs, err)
  22. }
  23. }
  24. return e
  25. }
  26. type joinError struct {
  27. errs []error
  28. }
  29. func (e *joinError) Error() string {
  30. if len(e.errs) == 1 {
  31. return strings.TrimSpace(e.errs[0].Error())
  32. }
  33. stringErrs := make([]string, 0, len(e.errs))
  34. for _, subErr := range e.errs {
  35. stringErrs = append(stringErrs, strings.Replace(subErr.Error(), "\n", "\n\t", -1))
  36. }
  37. return "* " + strings.Join(stringErrs, "\n* ")
  38. }
  39. func (e *joinError) Unwrap() []error {
  40. return e.errs
  41. }