本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

165 lines
4.4KB

  1. // Copyright 2015 go-swagger maintainers
  2. //
  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. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package errors
  15. import (
  16. "encoding/json"
  17. "fmt"
  18. "net/http"
  19. "reflect"
  20. "strings"
  21. )
  22. // DefaultHTTPCode is used when the error Code cannot be used as an HTTP code.
  23. var DefaultHTTPCode = http.StatusUnprocessableEntity
  24. // Error represents a error interface all swagger framework errors implement
  25. type Error interface {
  26. error
  27. Code() int32
  28. }
  29. type apiError struct {
  30. code int32
  31. message string
  32. }
  33. func (a *apiError) Error() string {
  34. return a.message
  35. }
  36. func (a *apiError) Code() int32 {
  37. return a.code
  38. }
  39. // New creates a new API error with a code and a message
  40. func New(code int32, message string, args ...interface{}) Error {
  41. if len(args) > 0 {
  42. return &apiError{code, fmt.Sprintf(message, args...)}
  43. }
  44. return &apiError{code, message}
  45. }
  46. // NotFound creates a new not found error
  47. func NotFound(message string, args ...interface{}) Error {
  48. if message == "" {
  49. message = "Not found"
  50. }
  51. return New(http.StatusNotFound, fmt.Sprintf(message, args...))
  52. }
  53. // NotImplemented creates a new not implemented error
  54. func NotImplemented(message string) Error {
  55. return New(http.StatusNotImplemented, message)
  56. }
  57. // MethodNotAllowedError represents an error for when the path matches but the method doesn't
  58. type MethodNotAllowedError struct {
  59. code int32
  60. Allowed []string
  61. message string
  62. }
  63. func (m *MethodNotAllowedError) Error() string {
  64. return m.message
  65. }
  66. // Code the error code
  67. func (m *MethodNotAllowedError) Code() int32 {
  68. return m.code
  69. }
  70. func errorAsJSON(err Error) []byte {
  71. b, _ := json.Marshal(struct {
  72. Code int32 `json:"code"`
  73. Message string `json:"message"`
  74. }{err.Code(), err.Error()})
  75. return b
  76. }
  77. func flattenComposite(errs *CompositeError) *CompositeError {
  78. var res []error
  79. for _, er := range errs.Errors {
  80. switch e := er.(type) {
  81. case *CompositeError:
  82. if len(e.Errors) > 0 {
  83. flat := flattenComposite(e)
  84. if len(flat.Errors) > 0 {
  85. res = append(res, flat.Errors...)
  86. }
  87. }
  88. default:
  89. if e != nil {
  90. res = append(res, e)
  91. }
  92. }
  93. }
  94. return CompositeValidationError(res...)
  95. }
  96. // MethodNotAllowed creates a new method not allowed error
  97. func MethodNotAllowed(requested string, allow []string) Error {
  98. msg := fmt.Sprintf("method %s is not allowed, but [%s] are", requested, strings.Join(allow, ","))
  99. return &MethodNotAllowedError{code: http.StatusMethodNotAllowed, Allowed: allow, message: msg}
  100. }
  101. // ServeError the error handler interface implementation
  102. func ServeError(rw http.ResponseWriter, r *http.Request, err error) {
  103. rw.Header().Set("Content-Type", "application/json")
  104. switch e := err.(type) {
  105. case *CompositeError:
  106. er := flattenComposite(e)
  107. // strips composite errors to first element only
  108. if len(er.Errors) > 0 {
  109. ServeError(rw, r, er.Errors[0])
  110. } else {
  111. // guard against empty CompositeError (invalid construct)
  112. ServeError(rw, r, nil)
  113. }
  114. case *MethodNotAllowedError:
  115. rw.Header().Add("Allow", strings.Join(err.(*MethodNotAllowedError).Allowed, ","))
  116. rw.WriteHeader(asHTTPCode(int(e.Code())))
  117. if r == nil || r.Method != http.MethodHead {
  118. _, _ = rw.Write(errorAsJSON(e))
  119. }
  120. case Error:
  121. value := reflect.ValueOf(e)
  122. if value.Kind() == reflect.Ptr && value.IsNil() {
  123. rw.WriteHeader(http.StatusInternalServerError)
  124. _, _ = rw.Write(errorAsJSON(New(http.StatusInternalServerError, "Unknown error")))
  125. return
  126. }
  127. rw.WriteHeader(asHTTPCode(int(e.Code())))
  128. if r == nil || r.Method != http.MethodHead {
  129. _, _ = rw.Write(errorAsJSON(e))
  130. }
  131. case nil:
  132. rw.WriteHeader(http.StatusInternalServerError)
  133. _, _ = rw.Write(errorAsJSON(New(http.StatusInternalServerError, "Unknown error")))
  134. default:
  135. rw.WriteHeader(http.StatusInternalServerError)
  136. if r == nil || r.Method != http.MethodHead {
  137. _, _ = rw.Write(errorAsJSON(New(http.StatusInternalServerError, err.Error())))
  138. }
  139. }
  140. }
  141. func asHTTPCode(input int) int {
  142. if input >= 600 {
  143. return DefaultHTTPCode
  144. }
  145. return input
  146. }
上海开阖软件有限公司 沪ICP备12045867号-1