4
0

error.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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 len(e.Msg) > 0 {
  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. return BadRequestErr(e, opts...)
  147. case http.StatusUnauthorized:
  148. return UnauthorizedErr(e, opts...)
  149. case http.StatusForbidden:
  150. return ForbiddenErr(e, opts...)
  151. case http.StatusInternalServerError:
  152. return InternalServerErr(e, opts...)
  153. case http.StatusNotImplemented:
  154. return NotImplementedErr(e, opts...)
  155. default:
  156. return UnexpectedErr(code, e, opts...)
  157. }
  158. }
  159. var (
  160. seeLogs = "Please see the certificate authority logs for more info."
  161. // BadRequestDefaultMsg 400 default msg
  162. BadRequestDefaultMsg = "The request could not be completed; malformed or missing data" + seeLogs
  163. // UnauthorizedDefaultMsg 401 default msg
  164. UnauthorizedDefaultMsg = "The request lacked necessary authorization to be completed. " + seeLogs
  165. // ForbiddenDefaultMsg 403 default msg
  166. ForbiddenDefaultMsg = "The request was forbidden by the certificate authority. " + seeLogs
  167. // NotFoundDefaultMsg 404 default msg
  168. NotFoundDefaultMsg = "The requested resource could not be found. " + seeLogs
  169. // InternalServerErrorDefaultMsg 500 default msg
  170. InternalServerErrorDefaultMsg = "The certificate authority encountered an Internal Server Error. " + seeLogs
  171. // NotImplementedDefaultMsg 501 default msg
  172. NotImplementedDefaultMsg = "The requested method is not implemented by the certificate authority. " + seeLogs
  173. )
  174. // splitOptionArgs splits the variadic length args into string formatting args
  175. // and Option(s) to apply to an Error.
  176. func splitOptionArgs(args []interface{}) ([]interface{}, []Option) {
  177. indexOptionStart := -1
  178. for i, a := range args {
  179. if _, ok := a.(Option); ok {
  180. indexOptionStart = i
  181. break
  182. }
  183. }
  184. if indexOptionStart < 0 {
  185. return args, []Option{}
  186. }
  187. opts := []Option{}
  188. // Ignore any non-Option args that come after the first Option.
  189. for _, o := range args[indexOptionStart:] {
  190. if opt, ok := o.(Option); ok {
  191. opts = append(opts, opt)
  192. }
  193. }
  194. return args[:indexOptionStart], opts
  195. }
  196. // NewErr returns a new Error. If the given error implements the StatusCoder
  197. // interface we will ignore the given status.
  198. func NewErr(status int, err error, opts ...Option) error {
  199. var (
  200. e *Error
  201. ok bool
  202. )
  203. if e, ok = err.(*Error); !ok {
  204. if sc, ok := err.(StatusCoder); ok {
  205. e = &Error{Status: sc.StatusCode(), Err: err}
  206. } else {
  207. cause := errors.Cause(err)
  208. if sc, ok := cause.(StatusCoder); ok {
  209. e = &Error{Status: sc.StatusCode(), Err: err}
  210. } else {
  211. e = &Error{Status: status, Err: err}
  212. }
  213. }
  214. }
  215. for _, o := range opts {
  216. o(e)
  217. }
  218. return e
  219. }
  220. // Errorf creates a new error using the given format and status code.
  221. func Errorf(code int, format string, args ...interface{}) error {
  222. as, opts := splitOptionArgs(args)
  223. opts = append(opts, withDefaultMessage(NotImplementedDefaultMsg))
  224. e := &Error{Status: code, Err: fmt.Errorf(format, as...)}
  225. for _, o := range opts {
  226. o(e)
  227. }
  228. return e
  229. }
  230. // InternalServer creates a 500 error with the given format and arguments.
  231. func InternalServer(format string, args ...interface{}) error {
  232. args = append(args, withDefaultMessage(InternalServerErrorDefaultMsg))
  233. return Errorf(http.StatusInternalServerError, format, args...)
  234. }
  235. // InternalServerErr returns a 500 error with the given error.
  236. func InternalServerErr(err error, opts ...Option) error {
  237. opts = append(opts, withDefaultMessage(InternalServerErrorDefaultMsg))
  238. return NewErr(http.StatusInternalServerError, err, opts...)
  239. }
  240. // NotImplemented creates a 501 error with the given format and arguments.
  241. func NotImplemented(format string, args ...interface{}) error {
  242. args = append(args, withDefaultMessage(NotImplementedDefaultMsg))
  243. return Errorf(http.StatusNotImplemented, format, args...)
  244. }
  245. // NotImplementedErr returns a 501 error with the given error.
  246. func NotImplementedErr(err error, opts ...Option) error {
  247. opts = append(opts, withDefaultMessage(NotImplementedDefaultMsg))
  248. return NewErr(http.StatusNotImplemented, err, opts...)
  249. }
  250. // BadRequest creates a 400 error with the given format and arguments.
  251. func BadRequest(format string, args ...interface{}) error {
  252. args = append(args, withDefaultMessage(BadRequestDefaultMsg))
  253. return Errorf(http.StatusBadRequest, format, args...)
  254. }
  255. // BadRequestErr returns an 400 error with the given error.
  256. func BadRequestErr(err error, opts ...Option) error {
  257. opts = append(opts, withDefaultMessage(BadRequestDefaultMsg))
  258. return NewErr(http.StatusBadRequest, err, opts...)
  259. }
  260. // Unauthorized creates a 401 error with the given format and arguments.
  261. func Unauthorized(format string, args ...interface{}) error {
  262. args = append(args, withDefaultMessage(UnauthorizedDefaultMsg))
  263. return Errorf(http.StatusUnauthorized, format, args...)
  264. }
  265. // UnauthorizedErr returns an 401 error with the given error.
  266. func UnauthorizedErr(err error, opts ...Option) error {
  267. opts = append(opts, withDefaultMessage(UnauthorizedDefaultMsg))
  268. return NewErr(http.StatusUnauthorized, err, opts...)
  269. }
  270. // Forbidden creates a 403 error with the given format and arguments.
  271. func Forbidden(format string, args ...interface{}) error {
  272. args = append(args, withDefaultMessage(ForbiddenDefaultMsg))
  273. return Errorf(http.StatusForbidden, format, args...)
  274. }
  275. // ForbiddenErr returns an 403 error with the given error.
  276. func ForbiddenErr(err error, opts ...Option) error {
  277. opts = append(opts, withDefaultMessage(ForbiddenDefaultMsg))
  278. return NewErr(http.StatusForbidden, err, opts...)
  279. }
  280. // NotFound creates a 404 error with the given format and arguments.
  281. func NotFound(format string, args ...interface{}) error {
  282. args = append(args, withDefaultMessage(NotFoundDefaultMsg))
  283. return Errorf(http.StatusNotFound, format, args...)
  284. }
  285. // NotFoundErr returns an 404 error with the given error.
  286. func NotFoundErr(err error, opts ...Option) error {
  287. opts = append(opts, withDefaultMessage(NotFoundDefaultMsg))
  288. return NewErr(http.StatusNotFound, err, opts...)
  289. }
  290. // UnexpectedErr will be used when the certificate authority makes an outgoing
  291. // request and receives an unhandled status code.
  292. func UnexpectedErr(code int, err error, opts ...Option) error {
  293. opts = append(opts, withDefaultMessage("The certificate authority received an "+
  294. "unexpected HTTP status code - '%d'. "+seeLogs, code))
  295. return NewErr(code, err, opts...)
  296. }