error.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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. // withDefaultMessage returns an Option that modifies the error by overwriting the
  19. // message only if it is empty.
  20. func withDefaultMessage(format string, args ...interface{}) Option {
  21. return func(e *Error) error {
  22. if e.Msg != "" {
  23. return e
  24. }
  25. e.Msg = fmt.Sprintf(format, args...)
  26. return e
  27. }
  28. }
  29. // WithMessage returns an Option that modifies the error by overwriting the
  30. // message only if it is empty.
  31. func WithMessage(format string, args ...interface{}) Option {
  32. return func(e *Error) error {
  33. e.Msg = fmt.Sprintf(format, args...)
  34. return e
  35. }
  36. }
  37. // WithKeyVal returns an Option that adds the given key-value pair to the
  38. // Error details. This is helpful for debugging errors.
  39. func WithKeyVal(key string, val interface{}) Option {
  40. return func(e *Error) error {
  41. if e.Details == nil {
  42. e.Details = make(map[string]interface{})
  43. }
  44. e.Details[key] = val
  45. return e
  46. }
  47. }
  48. // Error represents the CA API errors.
  49. type Error struct {
  50. Status int
  51. Err error
  52. Msg string
  53. Details map[string]interface{}
  54. }
  55. // ErrorResponse represents an error in JSON format.
  56. type ErrorResponse struct {
  57. Status int `json:"status"`
  58. Message string `json:"message"`
  59. }
  60. // Cause implements the errors.Causer interface and returns the original error.
  61. func (e *Error) Cause() error {
  62. return e.Err
  63. }
  64. // Error implements the error interface and returns the error string.
  65. func (e *Error) Error() string {
  66. return e.Err.Error()
  67. }
  68. // StatusCode implements the StatusCoder interface and returns the HTTP response
  69. // code.
  70. func (e *Error) StatusCode() int {
  71. return e.Status
  72. }
  73. // Message returns a user friendly error, if one is set.
  74. func (e *Error) Message() string {
  75. if len(e.Msg) > 0 {
  76. return e.Msg
  77. }
  78. return e.Err.Error()
  79. }
  80. // Wrap returns an error annotating err with a stack trace at the point Wrap is
  81. // called, and the supplied message. If err is nil, Wrap returns nil.
  82. func Wrap(status int, e error, m string, args ...interface{}) error {
  83. if e == nil {
  84. return nil
  85. }
  86. _, opts := splitOptionArgs(args)
  87. if err, ok := e.(*Error); ok {
  88. err.Err = errors.Wrap(err.Err, m)
  89. e = err
  90. } else {
  91. e = errors.Wrap(e, m)
  92. }
  93. return StatusCodeError(status, e, opts...)
  94. }
  95. // Wrapf returns an error annotating err with a stack trace at the point Wrap is
  96. // called, and the supplied message. If err is nil, Wrap returns nil.
  97. func Wrapf(status int, e error, format string, args ...interface{}) error {
  98. if e == nil {
  99. return nil
  100. }
  101. as, opts := splitOptionArgs(args)
  102. if err, ok := e.(*Error); ok {
  103. err.Err = errors.Wrapf(err.Err, format, args...)
  104. e = err
  105. } else {
  106. e = errors.Wrapf(e, format, as...)
  107. }
  108. return StatusCodeError(status, e, opts...)
  109. }
  110. // MarshalJSON implements json.Marshaller interface for the Error struct.
  111. func (e *Error) MarshalJSON() ([]byte, error) {
  112. var msg string
  113. if len(e.Msg) > 0 {
  114. msg = e.Msg
  115. } else {
  116. msg = http.StatusText(e.Status)
  117. }
  118. return json.Marshal(&ErrorResponse{Status: e.Status, Message: msg})
  119. }
  120. // UnmarshalJSON implements json.Unmarshaler interface for the Error struct.
  121. func (e *Error) UnmarshalJSON(data []byte) error {
  122. var er ErrorResponse
  123. if err := json.Unmarshal(data, &er); err != nil {
  124. return err
  125. }
  126. e.Status = er.Status
  127. e.Err = fmt.Errorf("%s", er.Message)
  128. return nil
  129. }
  130. // Format implements the fmt.Formatter interface.
  131. func (e *Error) Format(f fmt.State, c rune) {
  132. if err, ok := e.Err.(fmt.Formatter); ok {
  133. err.Format(f, c)
  134. return
  135. }
  136. fmt.Fprint(f, e.Err.Error())
  137. }
  138. // Messenger is a friendly message interface that errors can implement.
  139. type Messenger interface {
  140. Message() string
  141. }
  142. // StatusCodeError selects the proper error based on the status code.
  143. func StatusCodeError(code int, e error, opts ...Option) error {
  144. switch code {
  145. case http.StatusBadRequest:
  146. opts = append(opts, withDefaultMessage(BadRequestDefaultMsg))
  147. return NewErr(http.StatusBadRequest, e, opts...)
  148. case http.StatusUnauthorized:
  149. return UnauthorizedErr(e, opts...)
  150. case http.StatusForbidden:
  151. opts = append(opts, withDefaultMessage(ForbiddenDefaultMsg))
  152. return NewErr(http.StatusForbidden, e, opts...)
  153. case http.StatusInternalServerError:
  154. return InternalServerErr(e, opts...)
  155. case http.StatusNotImplemented:
  156. return NotImplementedErr(e, opts...)
  157. default:
  158. return UnexpectedErr(code, e, opts...)
  159. }
  160. }
  161. var (
  162. seeLogs = "Please see the certificate authority logs for more info."
  163. // BadRequestDefaultMsg 400 default msg
  164. BadRequestDefaultMsg = "The request could not be completed; malformed or missing data. " + seeLogs
  165. // UnauthorizedDefaultMsg 401 default msg
  166. UnauthorizedDefaultMsg = "The request lacked necessary authorization to be completed. " + seeLogs
  167. // ForbiddenDefaultMsg 403 default msg
  168. ForbiddenDefaultMsg = "The request was forbidden by the certificate authority. " + seeLogs
  169. // NotFoundDefaultMsg 404 default msg
  170. NotFoundDefaultMsg = "The requested resource could not be found. " + seeLogs
  171. // InternalServerErrorDefaultMsg 500 default msg
  172. InternalServerErrorDefaultMsg = "The certificate authority encountered an Internal Server Error. " + seeLogs
  173. // NotImplementedDefaultMsg 501 default msg
  174. NotImplementedDefaultMsg = "The requested method is not implemented by the certificate authority. " + seeLogs
  175. )
  176. var (
  177. // BadRequestPrefix is the prefix added to the bad request messages that are
  178. // directly sent to the cli.
  179. BadRequestPrefix = "The request could not be completed: "
  180. // ForbiddenPrefix is the prefix added to the forbidden messates that are
  181. // sent to the cli.
  182. ForbiddenPrefix = "The request was forbidden by the certificate authority: "
  183. )
  184. func formatMessage(status int, msg string) string {
  185. switch status {
  186. case http.StatusBadRequest:
  187. return BadRequestPrefix + msg + "."
  188. case http.StatusForbidden:
  189. return ForbiddenPrefix + msg + "."
  190. default:
  191. return msg
  192. }
  193. }
  194. // splitOptionArgs splits the variadic length args into string formatting args
  195. // and Option(s) to apply to an Error.
  196. func splitOptionArgs(args []interface{}) ([]interface{}, []Option) {
  197. indexOptionStart := -1
  198. for i, a := range args {
  199. if _, ok := a.(Option); ok {
  200. indexOptionStart = i
  201. break
  202. }
  203. }
  204. if indexOptionStart < 0 {
  205. return args, []Option{}
  206. }
  207. opts := []Option{}
  208. // Ignore any non-Option args that come after the first Option.
  209. for _, o := range args[indexOptionStart:] {
  210. if opt, ok := o.(Option); ok {
  211. opts = append(opts, opt)
  212. }
  213. }
  214. return args[:indexOptionStart], opts
  215. }
  216. // New creates a new http error with the given status and message.
  217. func New(status int, format string, args ...interface{}) error {
  218. msg := fmt.Sprintf(format, args...)
  219. return &Error{
  220. Status: status,
  221. Msg: formatMessage(status, msg),
  222. Err: errors.New(msg),
  223. }
  224. }
  225. // NewError creates a new http error with the given error and message.
  226. func NewError(status int, err error, format string, args ...interface{}) error {
  227. if _, ok := err.(*Error); ok {
  228. return err
  229. }
  230. msg := fmt.Sprintf(format, args...)
  231. if _, ok := err.(StackTracer); !ok {
  232. err = errors.Wrap(err, msg)
  233. }
  234. return &Error{
  235. Status: status,
  236. Msg: formatMessage(status, msg),
  237. Err: err,
  238. }
  239. }
  240. // NewErr returns a new Error. If the given error implements the StatusCoder
  241. // interface we will ignore the given status.
  242. func NewErr(status int, err error, opts ...Option) error {
  243. var (
  244. e *Error
  245. ok bool
  246. )
  247. if e, ok = err.(*Error); !ok {
  248. if sc, ok := err.(StatusCoder); ok {
  249. e = &Error{Status: sc.StatusCode(), Err: err}
  250. } else {
  251. cause := errors.Cause(err)
  252. if sc, ok := cause.(StatusCoder); ok {
  253. e = &Error{Status: sc.StatusCode(), Err: err}
  254. } else {
  255. e = &Error{Status: status, Err: err}
  256. }
  257. }
  258. }
  259. for _, o := range opts {
  260. o(e)
  261. }
  262. return e
  263. }
  264. // Errorf creates a new error using the given format and status code.
  265. func Errorf(code int, format string, args ...interface{}) error {
  266. as, opts := splitOptionArgs(args)
  267. opts = append(opts, withDefaultMessage(NotImplementedDefaultMsg))
  268. e := &Error{Status: code, Err: fmt.Errorf(format, as...)}
  269. for _, o := range opts {
  270. o(e)
  271. }
  272. return e
  273. }
  274. // ApplyOptions applies the given options to the error if is the type *Error.
  275. // TODO(mariano): try to get rid of this.
  276. func ApplyOptions(err error, opts ...interface{}) error {
  277. if e, ok := err.(*Error); ok {
  278. _, o := splitOptionArgs(opts)
  279. for _, fn := range o {
  280. fn(e)
  281. }
  282. }
  283. return err
  284. }
  285. // InternalServer creates a 500 error with the given format and arguments.
  286. func InternalServer(format string, args ...interface{}) error {
  287. args = append(args, withDefaultMessage(InternalServerErrorDefaultMsg))
  288. return Errorf(http.StatusInternalServerError, format, args...)
  289. }
  290. // InternalServerErr returns a 500 error with the given error.
  291. func InternalServerErr(err error, opts ...Option) error {
  292. opts = append(opts, withDefaultMessage(InternalServerErrorDefaultMsg))
  293. return NewErr(http.StatusInternalServerError, err, opts...)
  294. }
  295. // NotImplemented creates a 501 error with the given format and arguments.
  296. func NotImplemented(format string, args ...interface{}) error {
  297. args = append(args, withDefaultMessage(NotImplementedDefaultMsg))
  298. return Errorf(http.StatusNotImplemented, format, args...)
  299. }
  300. // NotImplementedErr returns a 501 error with the given error.
  301. func NotImplementedErr(err error, opts ...Option) error {
  302. opts = append(opts, withDefaultMessage(NotImplementedDefaultMsg))
  303. return NewErr(http.StatusNotImplemented, err, opts...)
  304. }
  305. // BadRequest creates a 400 error with the given format and arguments.
  306. func BadRequest(format string, args ...interface{}) error {
  307. return New(http.StatusBadRequest, format, args...)
  308. }
  309. // BadRequestErr returns an 400 error with the given error.
  310. func BadRequestErr(err error, format string, args ...interface{}) error {
  311. return NewError(http.StatusBadRequest, err, format, args...)
  312. }
  313. // Unauthorized creates a 401 error with the given format and arguments.
  314. func Unauthorized(format string, args ...interface{}) error {
  315. args = append(args, withDefaultMessage(UnauthorizedDefaultMsg))
  316. return Errorf(http.StatusUnauthorized, format, args...)
  317. }
  318. // UnauthorizedErr returns an 401 error with the given error.
  319. func UnauthorizedErr(err error, opts ...Option) error {
  320. opts = append(opts, withDefaultMessage(UnauthorizedDefaultMsg))
  321. return NewErr(http.StatusUnauthorized, err, opts...)
  322. }
  323. // Forbidden creates a 403 error with the given format and arguments.
  324. func Forbidden(format string, args ...interface{}) error {
  325. return New(http.StatusForbidden, format, args...)
  326. }
  327. // ForbiddenErr returns an 403 error with the given error.
  328. func ForbiddenErr(err error, format string, args ...interface{}) error {
  329. return NewError(http.StatusForbidden, err, format, args...)
  330. }
  331. // NotFound creates a 404 error with the given format and arguments.
  332. func NotFound(format string, args ...interface{}) error {
  333. args = append(args, withDefaultMessage(NotFoundDefaultMsg))
  334. return Errorf(http.StatusNotFound, format, args...)
  335. }
  336. // NotFoundErr returns an 404 error with the given error.
  337. func NotFoundErr(err error, opts ...Option) error {
  338. opts = append(opts, withDefaultMessage(NotFoundDefaultMsg))
  339. return NewErr(http.StatusNotFound, err, opts...)
  340. }
  341. // UnexpectedErr will be used when the certificate authority makes an outgoing
  342. // request and receives an unhandled status code.
  343. func UnexpectedErr(code int, err error, opts ...Option) error {
  344. opts = append(opts, withDefaultMessage("The certificate authority received an "+
  345. "unexpected HTTP status code - '%d'. "+seeLogs, code))
  346. return NewErr(code, err, opts...)
  347. }