errors.go 5.8 KB

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