You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

72 lines
1.8 KiB

  1. // Copyright 2015 Google Inc. All rights reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package martian
  15. import (
  16. "strings"
  17. "sync"
  18. )
  19. // MultiError is a collection of errors that implements the error interface.
  20. type MultiError struct {
  21. mu sync.RWMutex
  22. errs []error
  23. }
  24. // NewMultiError returns a new MultiError.
  25. func NewMultiError() *MultiError {
  26. return &MultiError{}
  27. }
  28. // Error returns the list of errors separated by newlines.
  29. func (merr *MultiError) Error() string {
  30. merr.mu.RLock()
  31. defer merr.mu.RUnlock()
  32. var errs []string
  33. for _, err := range merr.errs {
  34. errs = append(errs, err.Error())
  35. }
  36. return strings.Join(errs, "\n")
  37. }
  38. // Errors returns the error slice containing the error collection.
  39. func (merr *MultiError) Errors() []error {
  40. merr.mu.RLock()
  41. defer merr.mu.RUnlock()
  42. return merr.errs
  43. }
  44. // Add appends an error to the error collection.
  45. func (merr *MultiError) Add(err error) {
  46. merr.mu.Lock()
  47. defer merr.mu.Unlock()
  48. // Unwrap *MultiError to ensure that depth never exceeds 1.
  49. if merr2, ok := err.(*MultiError); ok {
  50. merr.errs = append(merr.errs, merr2.Errors()...)
  51. return
  52. }
  53. merr.errs = append(merr.errs, err)
  54. }
  55. // Empty returns whether the *MultiError contains any errors.
  56. func (merr *MultiError) Empty() bool {
  57. return len(merr.errs) == 0
  58. }