batcherror.go 884 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package errorx
  2. import "bytes"
  3. type (
  4. // A BatchError is an error that can hold multiple errors.
  5. BatchError struct {
  6. errs errorArray
  7. }
  8. errorArray []error
  9. )
  10. // Add adds errs to be, nil errors are ignored.
  11. func (be *BatchError) Add(errs ...error) {
  12. for _, err := range errs {
  13. if err != nil {
  14. be.errs = append(be.errs, err)
  15. }
  16. }
  17. }
  18. // Err returns an error that represents all errors.
  19. func (be *BatchError) Err() error {
  20. switch len(be.errs) {
  21. case 0:
  22. return nil
  23. case 1:
  24. return be.errs[0]
  25. default:
  26. return be.errs
  27. }
  28. }
  29. // NotNil checks if any error inside.
  30. func (be *BatchError) NotNil() bool {
  31. return len(be.errs) > 0
  32. }
  33. // Error returns a string that represents inside errors.
  34. func (ea errorArray) Error() string {
  35. var buf bytes.Buffer
  36. for i := range ea {
  37. if i > 0 {
  38. buf.WriteByte('\n')
  39. }
  40. buf.WriteString(ea[i].Error())
  41. }
  42. return buf.String()
  43. }