errors.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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. "k8s.io/apimachinery/pkg/util/sets"
  18. )
  19. // MessageCountMap contains occurrence for each error message.
  20. type MessageCountMap map[string]int
  21. // Aggregate represents an object that contains multiple errors, but does not
  22. // necessarily have singular semantic meaning.
  23. // The aggregate can be used with `errors.Is()` to check for the occurrence of
  24. // a specific error type.
  25. // Errors.As() is not supported, because the caller presumably cares about a
  26. // specific error of potentially multiple that match the given type.
  27. type Aggregate interface {
  28. error
  29. Errors() []error
  30. Is(error) bool
  31. }
  32. // NewAggregate converts a slice of errors into an Aggregate interface, which
  33. // is itself an implementation of the error interface. If the slice is empty,
  34. // this returns nil.
  35. // It will check if any of the element of input error list is nil, to avoid
  36. // nil pointer panic when call Error().
  37. func NewAggregate(errlist []error) Aggregate {
  38. if len(errlist) == 0 {
  39. return nil
  40. }
  41. // In case of input error list contains nil
  42. var errs []error
  43. for _, e := range errlist {
  44. if e != nil {
  45. errs = append(errs, e)
  46. }
  47. }
  48. if len(errs) == 0 {
  49. return nil
  50. }
  51. return aggregate(errs)
  52. }
  53. // This helper implements the error and Errors interfaces. Keeping it private
  54. // prevents people from making an aggregate of 0 errors, which is not
  55. // an error, but does satisfy the error interface.
  56. type aggregate []error
  57. // Error is part of the error interface.
  58. func (agg aggregate) Error() string {
  59. if len(agg) == 0 {
  60. // This should never happen, really.
  61. return ""
  62. }
  63. if len(agg) == 1 {
  64. return agg[0].Error()
  65. }
  66. seenerrs := sets.NewString()
  67. result := ""
  68. agg.visit(func(err error) bool {
  69. msg := err.Error()
  70. if seenerrs.Has(msg) {
  71. return false
  72. }
  73. seenerrs.Insert(msg)
  74. if len(seenerrs) > 1 {
  75. result += ", "
  76. }
  77. result += msg
  78. return false
  79. })
  80. if len(seenerrs) == 1 {
  81. return result
  82. }
  83. return "[" + result + "]"
  84. }
  85. func (agg aggregate) Is(target error) bool {
  86. return agg.visit(func(err error) bool {
  87. return errors.Is(err, target)
  88. })
  89. }
  90. func (agg aggregate) visit(f func(err error) bool) bool {
  91. for _, err := range agg {
  92. switch err := err.(type) {
  93. case aggregate:
  94. if match := err.visit(f); match {
  95. return match
  96. }
  97. case Aggregate:
  98. for _, nestedErr := range err.Errors() {
  99. if match := f(nestedErr); match {
  100. return match
  101. }
  102. }
  103. default:
  104. if match := f(err); match {
  105. return match
  106. }
  107. }
  108. }
  109. return false
  110. }
  111. // Errors is part of the Aggregate interface.
  112. func (agg aggregate) Errors() []error {
  113. return []error(agg)
  114. }
  115. // Matcher is used to match errors. Returns true if the error matches.
  116. type Matcher func(error) bool
  117. // FilterOut removes all errors that match any of the matchers from the input
  118. // error. If the input is a singular error, only that error is tested. If the
  119. // input implements the Aggregate interface, the list of errors will be
  120. // processed recursively.
  121. //
  122. // This can be used, for example, to remove known-OK errors (such as io.EOF or
  123. // os.PathNotFound) from a list of errors.
  124. func FilterOut(err error, fns ...Matcher) error {
  125. if err == nil {
  126. return nil
  127. }
  128. if agg, ok := err.(Aggregate); ok {
  129. return NewAggregate(filterErrors(agg.Errors(), fns...))
  130. }
  131. if !matchesError(err, fns...) {
  132. return err
  133. }
  134. return nil
  135. }
  136. // matchesError returns true if any Matcher returns true
  137. func matchesError(err error, fns ...Matcher) bool {
  138. for _, fn := range fns {
  139. if fn(err) {
  140. return true
  141. }
  142. }
  143. return false
  144. }
  145. // filterErrors returns any errors (or nested errors, if the list contains
  146. // nested Errors) for which all fns return false. If no errors
  147. // remain a nil list is returned. The resulting slice will have all
  148. // nested slices flattened as a side effect.
  149. func filterErrors(list []error, fns ...Matcher) []error {
  150. result := []error{}
  151. for _, err := range list {
  152. r := FilterOut(err, fns...)
  153. if r != nil {
  154. result = append(result, r)
  155. }
  156. }
  157. return result
  158. }
  159. // Flatten takes an Aggregate, which may hold other Aggregates in arbitrary
  160. // nesting, and flattens them all into a single Aggregate, recursively.
  161. func Flatten(agg Aggregate) Aggregate {
  162. result := []error{}
  163. if agg == nil {
  164. return nil
  165. }
  166. for _, err := range agg.Errors() {
  167. if a, ok := err.(Aggregate); ok {
  168. r := Flatten(a)
  169. if r != nil {
  170. result = append(result, r.Errors()...)
  171. }
  172. } else {
  173. if err != nil {
  174. result = append(result, err)
  175. }
  176. }
  177. }
  178. return NewAggregate(result)
  179. }
  180. // CreateAggregateFromMessageCountMap converts MessageCountMap Aggregate
  181. func CreateAggregateFromMessageCountMap(m MessageCountMap) Aggregate {
  182. if m == nil {
  183. return nil
  184. }
  185. result := make([]error, 0, len(m))
  186. for errStr, count := range m {
  187. var countStr string
  188. if count > 1 {
  189. countStr = fmt.Sprintf(" (repeated %v times)", count)
  190. }
  191. result = append(result, fmt.Errorf("%v%v", errStr, countStr))
  192. }
  193. return NewAggregate(result)
  194. }
  195. // Reduce will return err or, if err is an Aggregate and only has one item,
  196. // the first item in the aggregate.
  197. func Reduce(err error) error {
  198. if agg, ok := err.(Aggregate); ok && err != nil {
  199. switch len(agg.Errors()) {
  200. case 1:
  201. return agg.Errors()[0]
  202. case 0:
  203. return nil
  204. }
  205. }
  206. return err
  207. }
  208. // AggregateGoroutines runs the provided functions in parallel, stuffing all
  209. // non-nil errors into the returned Aggregate.
  210. // Returns nil if all the functions complete successfully.
  211. func AggregateGoroutines(funcs ...func() error) Aggregate {
  212. errChan := make(chan error, len(funcs))
  213. for _, f := range funcs {
  214. go func(f func() error) { errChan <- f() }(f)
  215. }
  216. errs := make([]error, 0)
  217. for i := 0; i < cap(errChan); i++ {
  218. if err := <-errChan; err != nil {
  219. errs = append(errs, err)
  220. }
  221. }
  222. return NewAggregate(errs)
  223. }
  224. // ErrPreconditionViolated is returned when the precondition is violated
  225. var ErrPreconditionViolated = errors.New("precondition is violated")