errors.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. Copyright 2014 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 content
  14. import (
  15. "fmt"
  16. "reflect"
  17. "k8s.io/apimachinery/pkg/api/validate/constraints"
  18. )
  19. // MinError returns a string explanation of a "must be greater than or equal"
  20. // validation failure.
  21. func MinError[T constraints.Integer](min T) string {
  22. return fmt.Sprintf("must be greater than or equal to %d", min)
  23. }
  24. // MaxLenError returns a string explanation of a "string too long" validation
  25. // failure.
  26. func MaxLenError(length int) string {
  27. return fmt.Sprintf("must be no more than %d bytes", length)
  28. }
  29. // EmptyError returns a string explanation of an "empty string" validation.
  30. func EmptyError() string {
  31. return "must be non-empty"
  32. }
  33. // RegexError returns a string explanation of a regex validation failure.
  34. func RegexError(msg string, re string, examples ...string) string {
  35. if len(examples) == 0 {
  36. return msg + " (regex used for validation is '" + re + "')"
  37. }
  38. msg += " (e.g. "
  39. for i := range examples {
  40. if i > 0 {
  41. msg += " or "
  42. }
  43. msg += "'" + examples[i] + "', "
  44. }
  45. msg += "regex used for validation is '" + re + "')"
  46. return msg
  47. }
  48. // NEQError returns a string explanation of a "must not be equal to" validation failure.
  49. func NEQError[T any](disallowed T) string {
  50. format := "%v"
  51. if reflect.ValueOf(disallowed).Kind() == reflect.String {
  52. format = "%q"
  53. }
  54. return fmt.Sprintf("must not be equal to "+format, disallowed)
  55. }