error.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /*
  2. Copyright 2021 The Rook Authors. All rights reserved.
  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 util
  14. import (
  15. "fmt"
  16. "github.com/pkg/errors"
  17. )
  18. // AggregateErrors takes a list of errors formats them into a pretty, user-readable list headed by
  19. // the text "errors:". All errors in the list will lose any context besides their error string.
  20. // If the errs list is empty, AggregateErrors returns nil.
  21. // Example:
  22. //
  23. // AggregateErrors(errList, "errors for my %q", "mom") -->
  24. // `errors for my "mom":
  25. // error 1
  26. // error 2
  27. // etc.`
  28. func AggregateErrors(errs []error, format string, args ...interface{}) error {
  29. if len(errs) == 0 {
  30. return nil
  31. }
  32. errString := fmt.Sprintf(format+":", args...)
  33. for _, err := range errs {
  34. errString = fmt.Sprintf("%s\n %s", errString, err.Error())
  35. }
  36. return errors.Errorf(errString)
  37. }