aggregate.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. Copyright 2018 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 errorutil
  14. import (
  15. "fmt"
  16. "strings"
  17. )
  18. // Aggregate represents an object that contains multiple errors, but does not
  19. // necessarily have singular semantic meaning.
  20. type Aggregate interface {
  21. error
  22. Errors() []error
  23. Strings() []string
  24. }
  25. // NewAggregate converts a slice of errors into an Aggregate interface, which
  26. // is itself an implementation of the error interface. If the slice is empty,
  27. // this returns nil.
  28. // It will check if any of the element of input error list is nil, to avoid
  29. // nil pointer panic when call Error().
  30. func NewAggregate(errlist ...error) Aggregate {
  31. if len(errlist) == 0 {
  32. return nil
  33. }
  34. // In case of input error list contains nil
  35. var errs []error
  36. for _, e := range errlist {
  37. if e != nil {
  38. errs = append(errs, e)
  39. }
  40. }
  41. if len(errs) == 0 {
  42. return nil
  43. }
  44. return aggregate(errs)
  45. }
  46. // This helper implements the error and Errors interfaces. Keeping it private
  47. // prevents people from making an aggregate of 0 errors, which is not
  48. // an error, but does satisfy the error interface.
  49. type aggregate []error
  50. // Error is part of the error interface.
  51. func (agg aggregate) Error() string {
  52. if len(agg) == 0 {
  53. // This should never happen, really.
  54. return ""
  55. }
  56. return fmt.Sprintf("[%s]", strings.Join(agg.Strings(), ", "))
  57. }
  58. // Strings flattens the aggregate (and any sub aggregates) into a
  59. // slice of strings.
  60. func (agg aggregate) Strings() []string {
  61. strs := make([]string, 0, len(agg))
  62. for _, e := range agg {
  63. if subAgg, ok := e.(aggregate); ok {
  64. strs = append(strs, subAgg.Strings()...)
  65. } else {
  66. strs = append(strs, e.Error())
  67. }
  68. }
  69. return strs
  70. }
  71. // Errors is part of the Aggregate interface.
  72. func (agg aggregate) Errors() []error {
  73. return []error(agg)
  74. }