4
0

error.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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(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. opts = append(opts, withDefaultMessage(InternalServerErrorDefaultMsg))
  155. return NewErr(http.StatusInternalServerError, e, opts...)
  156. case http.StatusNotImplemented:
  157. opts = append(opts, withDefaultMessage(NotImplementedDefaultMsg))
  158. return NewErr(http.StatusNotImplemented, e, opts...)
  159. default:
  160. return UnexpectedErr(code, e, opts...)
  161. }
  162. }
  163. var (
  164. seeLogs = "Please see the certificate authority logs for more info."
  165. // BadRequestDefaultMsg 400 default msg
  166. BadRequestDefaultMsg = "The request could not be completed; malformed or missing data. " + seeLogs
  167. // UnauthorizedDefaultMsg 401 default msg
  168. UnauthorizedDefaultMsg = "The request lacked necessary authorization to be completed. " + seeLogs
  169. // ForbiddenDefaultMsg 403 default msg
  170. ForbiddenDefaultMsg = "The request was forbidden by the certificate authority. " + seeLogs
  171. // NotFoundDefaultMsg 404 default msg
  172. NotFoundDefaultMsg = "The requested resource could not be found. " + seeLogs
  173. // InternalServerErrorDefaultMsg 500 default msg
  174. InternalServerErrorDefaultMsg = "The certificate authority encountered an Internal Server Error. " + seeLogs
  175. // NotImplementedDefaultMsg 501 default msg
  176. NotImplementedDefaultMsg = "The requested method is not implemented by the certificate authority. " + seeLogs
  177. )
  178. var (
  179. // BadRequestPrefix is the prefix added to the bad request messages that are
  180. // directly sent to the cli.
  181. BadRequestPrefix = "The request could not be completed: "
  182. // ForbiddenPrefix is the prefix added to the forbidden messages that are
  183. // sent to the cli.
  184. ForbiddenPrefix = "The request was forbidden by the certificate authority: "
  185. // InternalServerPrefix is the prefix added to the internal server error
  186. // messages that are sent to the cli.
  187. InternalServerPrefix = "The certificate authority encountered an Internal Server Error: "
  188. )
  189. func formatMessage(status int, msg string) string {
  190. switch status {
  191. case http.StatusBadRequest:
  192. return BadRequestPrefix + msg + "."
  193. case http.StatusForbidden:
  194. return ForbiddenPrefix + msg + "."
  195. case http.StatusInternalServerError:
  196. return InternalServerPrefix + msg + "."
  197. default:
  198. return msg
  199. }
  200. }
  201. // splitOptionArgs splits the variadic length args into string formatting args
  202. // and Option(s) to apply to an Error.
  203. func splitOptionArgs(args []interface{}) ([]interface{}, []Option) {
  204. indexOptionStart := -1
  205. for i, a := range args {
  206. if _, ok := a.(Option); ok {
  207. indexOptionStart = i
  208. break
  209. }
  210. }
  211. if indexOptionStart < 0 {
  212. return args, []Option{}
  213. }
  214. opts := []Option{}
  215. // Ignore any non-Option args that come after the first Option.
  216. for _, o := range args[indexOptionStart:] {
  217. if opt, ok := o.(Option); ok {
  218. opts = append(opts, opt)
  219. }
  220. }
  221. return args[:indexOptionStart], opts
  222. }
  223. // New creates a new http error with the given status and message.
  224. func New(status int, format string, args ...interface{}) error {
  225. msg := fmt.Sprintf(format, args...)
  226. return &Error{
  227. Status: status,
  228. Msg: formatMessage(status, msg),
  229. Err: errors.New(msg),
  230. }
  231. }
  232. // NewError creates a new http error with the given error and message.
  233. func NewError(status int, err error, format string, args ...interface{}) error {
  234. if _, ok := err.(*Error); ok {
  235. return err
  236. }
  237. msg := fmt.Sprintf(format, args...)
  238. if _, ok := err.(StackTracer); !ok {
  239. err = errors.Wrap(err, msg)
  240. }
  241. return &Error{
  242. Status: status,
  243. Msg: formatMessage(status, msg),
  244. Err: err,
  245. }
  246. }
  247. // NewErr returns a new Error. If the given error implements the StatusCoder
  248. // interface we will ignore the given status.
  249. func NewErr(status int, err error, opts ...Option) error {
  250. var (
  251. e *Error
  252. ok bool
  253. )
  254. if e, ok = err.(*Error); !ok {
  255. if sc, ok := err.(StatusCoder); ok {
  256. e = &Error{Status: sc.StatusCode(), Err: err}
  257. } else {
  258. cause := errors.Cause(err)
  259. if sc, ok := cause.(StatusCoder); ok {
  260. e = &Error{Status: sc.StatusCode(), Err: err}
  261. } else {
  262. e = &Error{Status: status, Err: err}
  263. }
  264. }
  265. }
  266. for _, o := range opts {
  267. o(e)
  268. }
  269. return e
  270. }
  271. // Errorf creates a new error using the given format and status code.
  272. func Errorf(code int, format string, args ...interface{}) error {
  273. as, opts := splitOptionArgs(args)
  274. opts = append(opts, withDefaultMessage(NotImplementedDefaultMsg))
  275. e := &Error{Status: code, Err: fmt.Errorf(format, as...)}
  276. for _, o := range opts {
  277. o(e)
  278. }
  279. return e
  280. }
  281. // ApplyOptions applies the given options to the error if is the type *Error.
  282. // TODO(mariano): try to get rid of this.
  283. func ApplyOptions(err error, opts ...interface{}) error {
  284. if e, ok := err.(*Error); ok {
  285. _, o := splitOptionArgs(opts)
  286. for _, fn := range o {
  287. fn(e)
  288. }
  289. }
  290. return err
  291. }
  292. // Internal creates a generic 500 error message with the a formatted error in
  293. // the logs.
  294. func Internal(format string, args ...interface{}) error {
  295. return InternalErr(fmt.Errorf(format, args...))
  296. }
  297. // Internal creates a generic 500 error message with the given error in the
  298. // logs.
  299. func InternalErr(err error) error {
  300. return NewError(http.StatusInternalServerError, err, InternalServerErrorDefaultMsg)
  301. }
  302. // InternalServer creates a 500 error with the given format and arguments.
  303. func InternalServer(format string, args ...interface{}) error {
  304. return New(http.StatusInternalServerError, format, args...)
  305. }
  306. // InternalServerErr returns a 500 error with the given error.
  307. func InternalServerErr(err error, format string, args ...interface{}) error {
  308. return NewError(http.StatusInternalServerError, err, format, args...)
  309. }
  310. // NotImplemented creates a 501 error with the given format and arguments.
  311. func NotImplemented(format string, args ...interface{}) error {
  312. args = append(args, withDefaultMessage(NotImplementedDefaultMsg))
  313. return Errorf(http.StatusNotImplemented, format, args...)
  314. }
  315. // NotImplementedErr returns a 501 error with the given error.
  316. func NotImplementedErr(err error, opts ...Option) error {
  317. opts = append(opts, withDefaultMessage(NotImplementedDefaultMsg))
  318. return NewErr(http.StatusNotImplemented, err, opts...)
  319. }
  320. // BadRequest creates a 400 error with the given format and arguments.
  321. func BadRequest(format string, args ...interface{}) error {
  322. return New(http.StatusBadRequest, format, args...)
  323. }
  324. // BadRequestErr returns an 400 error with the given error.
  325. func BadRequestErr(err error, format string, args ...interface{}) error {
  326. return NewError(http.StatusBadRequest, err, format, args...)
  327. }
  328. // Unauthorized creates a 401 error with the given format and arguments.
  329. func Unauthorized(format string, args ...interface{}) error {
  330. args = append(args, withDefaultMessage(UnauthorizedDefaultMsg))
  331. return Errorf(http.StatusUnauthorized, format, args...)
  332. }
  333. // UnauthorizedErr returns an 401 error with the given error.
  334. func UnauthorizedErr(err error, opts ...Option) error {
  335. opts = append(opts, withDefaultMessage(UnauthorizedDefaultMsg))
  336. return NewErr(http.StatusUnauthorized, err, opts...)
  337. }
  338. // Forbidden creates a 403 error with the given format and arguments.
  339. func Forbidden(format string, args ...interface{}) error {
  340. return New(http.StatusForbidden, format, args...)
  341. }
  342. // ForbiddenErr returns an 403 error with the given error.
  343. func ForbiddenErr(err error, format string, args ...interface{}) error {
  344. return NewError(http.StatusForbidden, err, format, args...)
  345. }
  346. // NotFound creates a 404 error with the given format and arguments.
  347. func NotFound(format string, args ...interface{}) error {
  348. args = append(args, withDefaultMessage(NotFoundDefaultMsg))
  349. return Errorf(http.StatusNotFound, format, args...)
  350. }
  351. // NotFoundErr returns an 404 error with the given error.
  352. func NotFoundErr(err error, opts ...Option) error {
  353. opts = append(opts, withDefaultMessage(NotFoundDefaultMsg))
  354. return NewErr(http.StatusNotFound, err, opts...)
  355. }
  356. // UnexpectedErr will be used when the certificate authority makes an outgoing
  357. // request and receives an unhandled status code.
  358. func UnexpectedErr(code int, err error, opts ...Option) error {
  359. opts = append(opts, withDefaultMessage("The certificate authority received an "+
  360. "unexpected HTTP status code - '%d'. "+seeLogs, code))
  361. return NewErr(code, err, opts...)
  362. }