error.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. package errs
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "github.com/pkg/errors"
  7. )
  8. // StatusCoder interface is used by errors that returns the HTTP response code.
  9. type StatusCoder interface {
  10. StatusCode() int
  11. }
  12. // StackTracer must be by those errors that return an stack trace.
  13. type StackTracer interface {
  14. StackTrace() errors.StackTrace
  15. }
  16. // Option modifies the Error type.
  17. type Option func(e *Error) error
  18. // WithMessage returns an Option that modifies the error by overwriting the
  19. // message only if it is empty.
  20. func WithMessage(format string, args ...interface{}) Option {
  21. return func(e *Error) error {
  22. if len(e.Msg) > 0 {
  23. return e
  24. }
  25. e.Msg = fmt.Sprintf(format, args...)
  26. return e
  27. }
  28. }
  29. // Error represents the CA API errors.
  30. type Error struct {
  31. Status int
  32. Err error
  33. Msg string
  34. }
  35. // New returns a new Error. If the given error implements the StatusCoder
  36. // interface we will ignore the given status.
  37. func New(status int, err error, opts ...Option) error {
  38. var e *Error
  39. if sc, ok := err.(StatusCoder); ok {
  40. e = &Error{Status: sc.StatusCode(), Err: err}
  41. } else {
  42. cause := errors.Cause(err)
  43. if sc, ok := cause.(StatusCoder); ok {
  44. e = &Error{Status: sc.StatusCode(), Err: err}
  45. } else {
  46. e = &Error{Status: status, Err: err}
  47. }
  48. }
  49. for _, o := range opts {
  50. o(e)
  51. }
  52. return e
  53. }
  54. // ErrorResponse represents an error in JSON format.
  55. type ErrorResponse struct {
  56. Status int `json:"status"`
  57. Message string `json:"message"`
  58. }
  59. // Cause implements the errors.Causer interface and returns the original error.
  60. func (e *Error) Cause() error {
  61. return e.Err
  62. }
  63. // Error implements the error interface and returns the error string.
  64. func (e *Error) Error() string {
  65. return e.Err.Error()
  66. }
  67. // StatusCode implements the StatusCoder interface and returns the HTTP response
  68. // code.
  69. func (e *Error) StatusCode() int {
  70. return e.Status
  71. }
  72. // Message returns a user friendly error, if one is set.
  73. func (e *Error) Message() string {
  74. if len(e.Msg) > 0 {
  75. return e.Msg
  76. }
  77. return e.Err.Error()
  78. }
  79. // Wrap returns an error annotating err with a stack trace at the point Wrap is
  80. // called, and the supplied message. If err is nil, Wrap returns nil.
  81. func Wrap(status int, e error, m string, opts ...Option) error {
  82. if e == nil {
  83. return nil
  84. }
  85. if err, ok := e.(*Error); ok {
  86. err.Err = errors.Wrap(err.Err, m)
  87. e = err
  88. } else {
  89. e = errors.Wrap(e, m)
  90. }
  91. return StatusCodeError(status, e, opts...)
  92. }
  93. // Wrapf returns an error annotating err with a stack trace at the point Wrap is
  94. // called, and the supplied message. If err is nil, Wrap returns nil.
  95. func Wrapf(status int, e error, format string, args ...interface{}) error {
  96. if e == nil {
  97. return nil
  98. }
  99. var opts []Option
  100. for i, arg := range args {
  101. // Once we find the first Option, assume that all further arguments are Options.
  102. if _, ok := arg.(Option); ok {
  103. for _, a := range args[i:] {
  104. // Ignore any arguments after the first Option that are not Options.
  105. if opt, ok := a.(Option); ok {
  106. opts = append(opts, opt)
  107. }
  108. }
  109. args = args[:i]
  110. break
  111. }
  112. }
  113. if err, ok := e.(*Error); ok {
  114. err.Err = errors.Wrapf(err.Err, format, args...)
  115. e = err
  116. } else {
  117. e = errors.Wrapf(e, format, args...)
  118. }
  119. return StatusCodeError(status, e, opts...)
  120. }
  121. // MarshalJSON implements json.Marshaller interface for the Error struct.
  122. func (e *Error) MarshalJSON() ([]byte, error) {
  123. var msg string
  124. if len(e.Msg) > 0 {
  125. msg = e.Msg
  126. } else {
  127. msg = http.StatusText(e.Status)
  128. }
  129. return json.Marshal(&ErrorResponse{Status: e.Status, Message: msg})
  130. }
  131. // UnmarshalJSON implements json.Unmarshaler interface for the Error struct.
  132. func (e *Error) UnmarshalJSON(data []byte) error {
  133. var er ErrorResponse
  134. if err := json.Unmarshal(data, &er); err != nil {
  135. return err
  136. }
  137. e.Status = er.Status
  138. e.Err = fmt.Errorf(er.Message)
  139. return nil
  140. }
  141. // Format implements the fmt.Formatter interface.
  142. func (e *Error) Format(f fmt.State, c rune) {
  143. if err, ok := e.Err.(fmt.Formatter); ok {
  144. err.Format(f, c)
  145. return
  146. }
  147. fmt.Fprint(f, e.Err.Error())
  148. }
  149. // Messenger is a friendly message interface that errors can implement.
  150. type Messenger interface {
  151. Message() string
  152. }
  153. // StatusCodeError selects the proper error based on the status code.
  154. func StatusCodeError(code int, e error, opts ...Option) error {
  155. switch code {
  156. case http.StatusBadRequest:
  157. return BadRequest(e, opts...)
  158. case http.StatusUnauthorized:
  159. return Unauthorized(e, opts...)
  160. case http.StatusForbidden:
  161. return Forbidden(e, opts...)
  162. case http.StatusInternalServerError:
  163. return InternalServerError(e, opts...)
  164. case http.StatusNotImplemented:
  165. return NotImplemented(e, opts...)
  166. default:
  167. return UnexpectedError(code, e, opts...)
  168. }
  169. }
  170. var seeLogs = "Please see the certificate authority logs for more info."
  171. // InternalServerError returns a 500 error with the given error.
  172. func InternalServerError(err error, opts ...Option) error {
  173. if len(opts) == 0 {
  174. opts = append(opts, WithMessage("The certificate authority encountered an Internal Server Error. "+seeLogs))
  175. }
  176. return New(http.StatusInternalServerError, err, opts...)
  177. }
  178. // NotImplemented returns a 501 error with the given error.
  179. func NotImplemented(err error, opts ...Option) error {
  180. if len(opts) == 0 {
  181. opts = append(opts, WithMessage("The requested method is not implemented by the certificate authority. "+seeLogs))
  182. }
  183. return New(http.StatusNotImplemented, err, opts...)
  184. }
  185. // BadRequest returns an 400 error with the given error.
  186. func BadRequest(err error, opts ...Option) error {
  187. if len(opts) == 0 {
  188. opts = append(opts, WithMessage("The request could not be completed due to being poorly formatted or "+
  189. "missing critical data. "+seeLogs))
  190. }
  191. return New(http.StatusBadRequest, err, opts...)
  192. }
  193. // Unauthorized returns an 401 error with the given error.
  194. func Unauthorized(err error, opts ...Option) error {
  195. if len(opts) == 0 {
  196. opts = append(opts, WithMessage("The request lacked necessary authorization to be completed. "+seeLogs))
  197. }
  198. return New(http.StatusUnauthorized, err, opts...)
  199. }
  200. // Forbidden returns an 403 error with the given error.
  201. func Forbidden(err error, opts ...Option) error {
  202. if len(opts) == 0 {
  203. opts = append(opts, WithMessage("The request was Forbidden by the certificate authority. "+seeLogs))
  204. }
  205. return New(http.StatusForbidden, err, opts...)
  206. }
  207. // NotFound returns an 404 error with the given error.
  208. func NotFound(err error, opts ...Option) error {
  209. if len(opts) == 0 {
  210. opts = append(opts, WithMessage("The requested resource could not be found. "+seeLogs))
  211. }
  212. return New(http.StatusNotFound, err, opts...)
  213. }
  214. // UnexpectedError will be used when the certificate authority makes an outgoing
  215. // request and receives an unhandled status code.
  216. func UnexpectedError(code int, err error, opts ...Option) error {
  217. if len(opts) == 0 {
  218. opts = append(opts, WithMessage("The certificate authority received an "+
  219. "unexpected HTTP status code - '%d'. "+seeLogs, code))
  220. }
  221. return New(code, err, opts...)
  222. }