multierror.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package multierror
  2. import (
  3. "strings"
  4. "github.com/hashicorp/go-multierror"
  5. )
  6. // Error wraps a multierror.Error and defines a default
  7. // formatting function that fits cli needs
  8. type Error struct {
  9. err *multierror.Error
  10. }
  11. func (e *Error) Error() string {
  12. if e == nil || e.err == nil {
  13. return ""
  14. }
  15. e.err.ErrorFormat = listErrorFunc
  16. return e.err.Error()
  17. }
  18. // WrappedErrors returns the list of errors that this Error is wrapping.
  19. // It is an implementation of the errwrap.Wrapper interface so that
  20. // multierror.Error can be used with that library.
  21. //
  22. // This method is not safe to be called concurrently and is no different
  23. // than accessing the Errors field directly. It is implemented only to
  24. // satisfy the errwrap.Wrapper interface.
  25. func (e *Error) WrappedErrors() []error {
  26. return e.err.WrappedErrors()
  27. }
  28. // Unwrap returns an error from Error (or nil if there are no errors)
  29. func (e *Error) Unwrap() error {
  30. if e == nil || e.err == nil {
  31. return nil
  32. }
  33. return e.err.Unwrap()
  34. }
  35. // ErrorOrNil returns an error interface if this Error represents
  36. // a list of errors, or returns nil if the list of errors is empty. This
  37. // function is useful at the end of accumulation to make sure that the value
  38. // returned represents the existence of errors.
  39. func (e *Error) ErrorOrNil() error {
  40. if e == nil || e.err == nil {
  41. return nil
  42. }
  43. if len(e.err.Errors) == 0 {
  44. return nil
  45. }
  46. return e
  47. }
  48. // Append adds an error to a multierror, if err is
  49. // not a multierror it will be converted to one
  50. func Append(err error, errs ...error) *Error {
  51. switch err := err.(type) {
  52. case *Error:
  53. if err == nil {
  54. err = new(Error)
  55. }
  56. for _, e := range errs {
  57. err.err = multierror.Append(err.err, e)
  58. }
  59. return err
  60. default:
  61. newErrs := make([]error, 0, len(errs)+1)
  62. if err != nil {
  63. newErrs = append(newErrs, err)
  64. }
  65. newErrs = append(newErrs, errs...)
  66. return Append(&Error{}, newErrs...)
  67. }
  68. }
  69. func listErrorFunc(errs []error) string {
  70. if len(errs) == 1 {
  71. return errs[0].Error()
  72. }
  73. messages := make([]string, len(errs))
  74. for i, err := range errs {
  75. messages[i] = "Error: " + err.Error()
  76. }
  77. return strings.Join(messages, "\n")
  78. }