errors.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. /*
  2. Copyright 2015 The Kubernetes Authors.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package errors
  14. import (
  15. "errors"
  16. "fmt"
  17. )
  18. // MessageCountMap contains occurrence for each error message.
  19. type MessageCountMap map[string]int
  20. // Aggregate represents an object that contains multiple errors, but does not
  21. // necessarily have singular semantic meaning.
  22. type Aggregate interface {
  23. error
  24. Errors() []error
  25. }
  26. // NewAggregate converts a slice of errors into an Aggregate interface, which
  27. // is itself an implementation of the error interface. If the slice is empty,
  28. // this returns nil.
  29. // It will check if any of the element of input error list is nil, to avoid
  30. // nil pointer panic when call Error().
  31. func NewAggregate(errlist []error) Aggregate {
  32. if len(errlist) == 0 {
  33. return nil
  34. }
  35. // In case of input error list contains nil
  36. var errs []error
  37. for _, e := range errlist {
  38. if e != nil {
  39. errs = append(errs, e)
  40. }
  41. }
  42. if len(errs) == 0 {
  43. return nil
  44. }
  45. return aggregate(errs)
  46. }
  47. // This helper implements the error and Errors interfaces. Keeping it private
  48. // prevents people from making an aggregate of 0 errors, which is not
  49. // an error, but does satisfy the error interface.
  50. type aggregate []error
  51. // Error is part of the error interface.
  52. func (agg aggregate) Error() string {
  53. if len(agg) == 0 {
  54. // This should never happen, really.
  55. return ""
  56. }
  57. if len(agg) == 1 {
  58. return agg[0].Error()
  59. }
  60. result := fmt.Sprintf("[%s", agg[0].Error())
  61. for i := 1; i < len(agg); i++ {
  62. result += fmt.Sprintf(", %s", agg[i].Error())
  63. }
  64. result += "]"
  65. return result
  66. }
  67. // Errors is part of the Aggregate interface.
  68. func (agg aggregate) Errors() []error {
  69. return []error(agg)
  70. }
  71. // Matcher is used to match errors. Returns true if the error matches.
  72. type Matcher func(error) bool
  73. // FilterOut removes all errors that match any of the matchers from the input
  74. // error. If the input is a singular error, only that error is tested. If the
  75. // input implements the Aggregate interface, the list of errors will be
  76. // processed recursively.
  77. //
  78. // This can be used, for example, to remove known-OK errors (such as io.EOF or
  79. // os.PathNotFound) from a list of errors.
  80. func FilterOut(err error, fns ...Matcher) error {
  81. if err == nil {
  82. return nil
  83. }
  84. if agg, ok := err.(Aggregate); ok {
  85. return NewAggregate(filterErrors(agg.Errors(), fns...))
  86. }
  87. if !matchesError(err, fns...) {
  88. return err
  89. }
  90. return nil
  91. }
  92. // matchesError returns true if any Matcher returns true
  93. func matchesError(err error, fns ...Matcher) bool {
  94. for _, fn := range fns {
  95. if fn(err) {
  96. return true
  97. }
  98. }
  99. return false
  100. }
  101. // filterErrors returns any errors (or nested errors, if the list contains
  102. // nested Errors) for which all fns return false. If no errors
  103. // remain a nil list is returned. The resulting silec will have all
  104. // nested slices flattened as a side effect.
  105. func filterErrors(list []error, fns ...Matcher) []error {
  106. result := []error{}
  107. for _, err := range list {
  108. r := FilterOut(err, fns...)
  109. if r != nil {
  110. result = append(result, r)
  111. }
  112. }
  113. return result
  114. }
  115. // Flatten takes an Aggregate, which may hold other Aggregates in arbitrary
  116. // nesting, and flattens them all into a single Aggregate, recursively.
  117. func Flatten(agg Aggregate) Aggregate {
  118. result := []error{}
  119. if agg == nil {
  120. return nil
  121. }
  122. for _, err := range agg.Errors() {
  123. if a, ok := err.(Aggregate); ok {
  124. r := Flatten(a)
  125. if r != nil {
  126. result = append(result, r.Errors()...)
  127. }
  128. } else {
  129. if err != nil {
  130. result = append(result, err)
  131. }
  132. }
  133. }
  134. return NewAggregate(result)
  135. }
  136. // CreateAggregateFromMessageCountMap converts MessageCountMap Aggregate
  137. func CreateAggregateFromMessageCountMap(m MessageCountMap) Aggregate {
  138. if m == nil {
  139. return nil
  140. }
  141. result := make([]error, 0, len(m))
  142. for errStr, count := range m {
  143. var countStr string
  144. if count > 1 {
  145. countStr = fmt.Sprintf(" (repeated %v times)", count)
  146. }
  147. result = append(result, fmt.Errorf("%v%v", errStr, countStr))
  148. }
  149. return NewAggregate(result)
  150. }
  151. // Reduce will return err or, if err is an Aggregate and only has one item,
  152. // the first item in the aggregate.
  153. func Reduce(err error) error {
  154. if agg, ok := err.(Aggregate); ok && err != nil {
  155. switch len(agg.Errors()) {
  156. case 1:
  157. return agg.Errors()[0]
  158. case 0:
  159. return nil
  160. }
  161. }
  162. return err
  163. }
  164. // AggregateGoroutines runs the provided functions in parallel, stuffing all
  165. // non-nil errors into the returned Aggregate.
  166. // Returns nil if all the functions complete successfully.
  167. func AggregateGoroutines(funcs ...func() error) Aggregate {
  168. errChan := make(chan error, len(funcs))
  169. for _, f := range funcs {
  170. go func(f func() error) { errChan <- f() }(f)
  171. }
  172. errs := make([]error, 0)
  173. for i := 0; i < cap(errChan); i++ {
  174. if err := <-errChan; err != nil {
  175. errs = append(errs, err)
  176. }
  177. }
  178. return NewAggregate(errs)
  179. }
  180. // ErrPreconditionViolated is returned when the precondition is violated
  181. var ErrPreconditionViolated = errors.New("precondition is violated")