error.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. Copyright 2016 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 util
  14. import (
  15. "fmt"
  16. "os"
  17. "strings"
  18. errorsutil "k8s.io/apimachinery/pkg/util/errors"
  19. )
  20. const (
  21. // DefaultErrorExitCode defines exit the code for failed action generally
  22. DefaultErrorExitCode = 1
  23. // PreFlightExitCode defines exit the code for preflight checks
  24. PreFlightExitCode = 2
  25. // ValidationExitCode defines the exit code validation checks
  26. ValidationExitCode = 3
  27. )
  28. // fatal prints the message if set and then exits.
  29. func fatal(msg string, code int) {
  30. if len(msg) > 0 {
  31. // add newline if needed
  32. if !strings.HasSuffix(msg, "\n") {
  33. msg += "\n"
  34. }
  35. fmt.Fprint(os.Stderr, msg)
  36. }
  37. os.Exit(code)
  38. }
  39. // CheckErr prints a user friendly error to STDERR and exits with a non-zero
  40. // exit code. Unrecognized errors will be printed with an "error: " prefix.
  41. //
  42. // This method is generic to the command in use and may be used by non-Kubectl
  43. // commands.
  44. func CheckErr(err error) {
  45. checkErr(err, fatal)
  46. }
  47. // preflightError allows us to know if the error is a preflight error or not
  48. // defining the interface here avoids an import cycle of pulling in preflight into the util package
  49. type preflightError interface {
  50. Preflight() bool
  51. }
  52. // checkErr formats a given error as a string and calls the passed handleErr
  53. // func with that string and an exit code.
  54. func checkErr(err error, handleErr func(string, int)) {
  55. switch err.(type) {
  56. case nil:
  57. return
  58. case preflightError:
  59. handleErr(err.Error(), PreFlightExitCode)
  60. case errorsutil.Aggregate:
  61. handleErr(err.Error(), ValidationExitCode)
  62. default:
  63. handleErr(err.Error(), DefaultErrorExitCode)
  64. }
  65. }
  66. // FormatErrMsg returns a human-readable string describing the slice of errors passed to the function
  67. func FormatErrMsg(errs []error) string {
  68. var errMsg string
  69. for _, err := range errs {
  70. errMsg = fmt.Sprintf("%s\t- %s\n", errMsg, err.Error())
  71. }
  72. return errMsg
  73. }