api.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  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 = 422
  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. const head = "HEAD"
  102. // ServeError the error handler interface implementation
  103. func ServeError(rw http.ResponseWriter, r *http.Request, err error) {
  104. rw.Header().Set("Content-Type", "application/json")
  105. switch e := err.(type) {
  106. case *CompositeError:
  107. er := flattenComposite(e)
  108. // strips composite errors to first element only
  109. if len(er.Errors) > 0 {
  110. ServeError(rw, r, er.Errors[0])
  111. } else {
  112. // guard against empty CompositeError (invalid construct)
  113. ServeError(rw, r, nil)
  114. }
  115. case *MethodNotAllowedError:
  116. rw.Header().Add("Allow", strings.Join(err.(*MethodNotAllowedError).Allowed, ","))
  117. rw.WriteHeader(asHTTPCode(int(e.Code())))
  118. if r == nil || r.Method != head {
  119. rw.Write(errorAsJSON(e))
  120. }
  121. case Error:
  122. value := reflect.ValueOf(e)
  123. if value.Kind() == reflect.Ptr && value.IsNil() {
  124. rw.WriteHeader(http.StatusInternalServerError)
  125. rw.Write(errorAsJSON(New(http.StatusInternalServerError, "Unknown error")))
  126. return
  127. }
  128. rw.WriteHeader(asHTTPCode(int(e.Code())))
  129. if r == nil || r.Method != head {
  130. rw.Write(errorAsJSON(e))
  131. }
  132. case nil:
  133. rw.WriteHeader(http.StatusInternalServerError)
  134. rw.Write(errorAsJSON(New(http.StatusInternalServerError, "Unknown error")))
  135. default:
  136. rw.WriteHeader(http.StatusInternalServerError)
  137. if r == nil || r.Method != head {
  138. rw.Write(errorAsJSON(New(http.StatusInternalServerError, err.Error())))
  139. }
  140. }
  141. }
  142. func asHTTPCode(input int) int {
  143. if input >= 600 {
  144. return DefaultHTTPCode
  145. }
  146. return input
  147. }