errors.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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 field
  14. import (
  15. "encoding/json"
  16. "fmt"
  17. "strings"
  18. utilerrors "k8s.io/kubernetes/pkg/util/errors"
  19. )
  20. // Error is an implementation of the 'error' interface, which represents a
  21. // field-level validation error.
  22. type Error struct {
  23. Type ErrorType
  24. Field string
  25. BadValue interface{}
  26. Detail string
  27. }
  28. var _ error = &Error{}
  29. // Error implements the error interface.
  30. func (v *Error) Error() string {
  31. return fmt.Sprintf("%s: %s", v.Field, v.ErrorBody())
  32. }
  33. // ErrorBody returns the error message without the field name. This is useful
  34. // for building nice-looking higher-level error reporting.
  35. func (v *Error) ErrorBody() string {
  36. var s string
  37. switch v.Type {
  38. case ErrorTypeRequired, ErrorTypeForbidden, ErrorTypeTooLong, ErrorTypeInternal:
  39. s = fmt.Sprintf("%s", v.Type)
  40. default:
  41. var bad string
  42. badBytes, err := json.Marshal(v.BadValue)
  43. if err != nil {
  44. bad = err.Error()
  45. } else {
  46. bad = string(badBytes)
  47. }
  48. s = fmt.Sprintf("%s: %s", v.Type, bad)
  49. }
  50. if len(v.Detail) != 0 {
  51. s += fmt.Sprintf(": %s", v.Detail)
  52. }
  53. return s
  54. }
  55. // ErrorType is a machine readable value providing more detail about why
  56. // a field is invalid. These values are expected to match 1-1 with
  57. // CauseType in api/types.go.
  58. type ErrorType string
  59. // TODO: These values are duplicated in api/types.go, but there's a circular dep. Fix it.
  60. const (
  61. // ErrorTypeNotFound is used to report failure to find a requested value
  62. // (e.g. looking up an ID). See NotFound().
  63. ErrorTypeNotFound ErrorType = "FieldValueNotFound"
  64. // ErrorTypeRequired is used to report required values that are not
  65. // provided (e.g. empty strings, null values, or empty arrays). See
  66. // Required().
  67. ErrorTypeRequired ErrorType = "FieldValueRequired"
  68. // ErrorTypeDuplicate is used to report collisions of values that must be
  69. // unique (e.g. unique IDs). See Duplicate().
  70. ErrorTypeDuplicate ErrorType = "FieldValueDuplicate"
  71. // ErrorTypeInvalid is used to report malformed values (e.g. failed regex
  72. // match, too long, out of bounds). See Invalid().
  73. ErrorTypeInvalid ErrorType = "FieldValueInvalid"
  74. // ErrorTypeNotSupported is used to report unknown values for enumerated
  75. // fields (e.g. a list of valid values). See NotSupported().
  76. ErrorTypeNotSupported ErrorType = "FieldValueNotSupported"
  77. // ErrorTypeForbidden is used to report valid (as per formatting rules)
  78. // values which would be accepted under some conditions, but which are not
  79. // permitted by the current conditions (such as security policy). See
  80. // Forbidden().
  81. ErrorTypeForbidden ErrorType = "FieldValueForbidden"
  82. // ErrorTypeTooLong is used to report that the given value is too long.
  83. // This is similar to ErrorTypeInvalid, but the error will not include the
  84. // too-long value. See TooLong().
  85. ErrorTypeTooLong ErrorType = "FieldValueTooLong"
  86. // ErrorTypeInternal is used to report other errors that are not related
  87. // to user input. See InternalError().
  88. ErrorTypeInternal ErrorType = "InternalError"
  89. )
  90. // String converts a ErrorType into its corresponding canonical error message.
  91. func (t ErrorType) String() string {
  92. switch t {
  93. case ErrorTypeNotFound:
  94. return "Not found"
  95. case ErrorTypeRequired:
  96. return "Required value"
  97. case ErrorTypeDuplicate:
  98. return "Duplicate value"
  99. case ErrorTypeInvalid:
  100. return "Invalid value"
  101. case ErrorTypeNotSupported:
  102. return "Unsupported value"
  103. case ErrorTypeForbidden:
  104. return "Forbidden"
  105. case ErrorTypeTooLong:
  106. return "Too long"
  107. case ErrorTypeInternal:
  108. return "Internal error"
  109. default:
  110. panic(fmt.Sprintf("unrecognized validation error: %q", string(t)))
  111. }
  112. }
  113. // NotFound returns a *Error indicating "value not found". This is
  114. // used to report failure to find a requested value (e.g. looking up an ID).
  115. func NotFound(field *Path, value interface{}) *Error {
  116. return &Error{ErrorTypeNotFound, field.String(), value, ""}
  117. }
  118. // Required returns a *Error indicating "value required". This is used
  119. // to report required values that are not provided (e.g. empty strings, null
  120. // values, or empty arrays).
  121. func Required(field *Path, detail string) *Error {
  122. return &Error{ErrorTypeRequired, field.String(), "", detail}
  123. }
  124. // Duplicate returns a *Error indicating "duplicate value". This is
  125. // used to report collisions of values that must be unique (e.g. names or IDs).
  126. func Duplicate(field *Path, value interface{}) *Error {
  127. return &Error{ErrorTypeDuplicate, field.String(), value, ""}
  128. }
  129. // Invalid returns a *Error indicating "invalid value". This is used
  130. // to report malformed values (e.g. failed regex match, too long, out of bounds).
  131. func Invalid(field *Path, value interface{}, detail string) *Error {
  132. return &Error{ErrorTypeInvalid, field.String(), value, detail}
  133. }
  134. // NotSupported returns a *Error indicating "unsupported value".
  135. // This is used to report unknown values for enumerated fields (e.g. a list of
  136. // valid values).
  137. func NotSupported(field *Path, value interface{}, validValues []string) *Error {
  138. detail := ""
  139. if validValues != nil && len(validValues) > 0 {
  140. detail = "supported values: " + strings.Join(validValues, ", ")
  141. }
  142. return &Error{ErrorTypeNotSupported, field.String(), value, detail}
  143. }
  144. // Forbidden returns a *Error indicating "forbidden". This is used to
  145. // report valid (as per formatting rules) values which would be accepted under
  146. // some conditions, but which are not permitted by current conditions (e.g.
  147. // security policy).
  148. func Forbidden(field *Path, detail string) *Error {
  149. return &Error{ErrorTypeForbidden, field.String(), "", detail}
  150. }
  151. // TooLong returns a *Error indicating "too long". This is used to
  152. // report that the given value is too long. This is similar to
  153. // Invalid, but the returned error will not include the too-long
  154. // value.
  155. func TooLong(field *Path, value interface{}, maxLength int) *Error {
  156. return &Error{ErrorTypeTooLong, field.String(), value, fmt.Sprintf("must have at most %d characters", maxLength)}
  157. }
  158. // InternalError returns a *Error indicating "internal error". This is used
  159. // to signal that an error was found that was not directly related to user
  160. // input. The err argument must be non-nil.
  161. func InternalError(field *Path, err error) *Error {
  162. return &Error{ErrorTypeInternal, field.String(), nil, err.Error()}
  163. }
  164. // ErrorList holds a set of Errors. It is plausible that we might one day have
  165. // non-field errors in this same umbrella package, but for now we don't, so
  166. // we can keep it simple and leave ErrorList here.
  167. type ErrorList []*Error
  168. // NewErrorTypeMatcher returns an errors.Matcher that returns true
  169. // if the provided error is a Error and has the provided ErrorType.
  170. func NewErrorTypeMatcher(t ErrorType) utilerrors.Matcher {
  171. return func(err error) bool {
  172. if e, ok := err.(*Error); ok {
  173. return e.Type == t
  174. }
  175. return false
  176. }
  177. }
  178. // ToAggregate converts the ErrorList into an errors.Aggregate.
  179. func (list ErrorList) ToAggregate() utilerrors.Aggregate {
  180. errs := make([]error, len(list))
  181. for i := range list {
  182. errs[i] = list[i]
  183. }
  184. return utilerrors.NewAggregate(errs)
  185. }
  186. func fromAggregate(agg utilerrors.Aggregate) ErrorList {
  187. errs := agg.Errors()
  188. list := make(ErrorList, len(errs))
  189. for i := range errs {
  190. list[i] = errs[i].(*Error)
  191. }
  192. return list
  193. }
  194. // Filter removes items from the ErrorList that match the provided fns.
  195. func (list ErrorList) Filter(fns ...utilerrors.Matcher) ErrorList {
  196. err := utilerrors.FilterOut(list.ToAggregate(), fns...)
  197. if err == nil {
  198. return nil
  199. }
  200. // FilterOut takes an Aggregate and returns an Aggregate
  201. return fromAggregate(err.(utilerrors.Aggregate))
  202. }