errors.go 681 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. package errors
  2. import "sync"
  3. // Error collection helper
  4. type ErrorCollector struct {
  5. m sync.Mutex
  6. errors []error
  7. }
  8. // Reports an error to the collector. Ignores if the error is nil.
  9. func (ec *ErrorCollector) Report(e error) {
  10. if e == nil {
  11. return
  12. }
  13. ec.m.Lock()
  14. defer ec.m.Unlock()
  15. ec.errors = append(ec.errors, e)
  16. }
  17. // Whether or not the collector caught errors
  18. func (ec *ErrorCollector) IsError() bool {
  19. ec.m.Lock()
  20. defer ec.m.Unlock()
  21. return len(ec.errors) > 0
  22. }
  23. // Errors caught by the collector
  24. func (ec *ErrorCollector) Errors() []error {
  25. ec.m.Lock()
  26. defer ec.m.Unlock()
  27. errs := make([]error, len(ec.errors))
  28. copy(errs, ec.errors)
  29. return errs
  30. }