errors.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. package api
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "os"
  7. "github.com/pkg/errors"
  8. "github.com/smallstep/ca-component/logging"
  9. )
  10. // StatusCoder interface is used by errors that returns the HTTP response code.
  11. type StatusCoder interface {
  12. StatusCode() int
  13. }
  14. // StackTracer must be by those errors that return an stack trace.
  15. type StackTracer interface {
  16. StackTrace() errors.StackTrace
  17. }
  18. // Error represents the CA API errors.
  19. type Error struct {
  20. Status int
  21. Err error
  22. }
  23. // ErrorResponse represents an error in JSON format.
  24. type ErrorResponse struct {
  25. Status int `json:"status"`
  26. Message string `json:"message"`
  27. }
  28. // Cause implements the errors.Causer interface and returns the original error.
  29. func (e *Error) Cause() error {
  30. return e.Err
  31. }
  32. // Error implements the error interface and returns the error string.
  33. func (e *Error) Error() string {
  34. return e.Err.Error()
  35. }
  36. // StatusCode implements the StatusCoder interface and returns the HTTP response
  37. // code.
  38. func (e *Error) StatusCode() int {
  39. return e.Status
  40. }
  41. // MarshalJSON implements json.Marshaller interface for the Error struct.
  42. func (e *Error) MarshalJSON() ([]byte, error) {
  43. return json.Marshal(&ErrorResponse{Status: e.Status, Message: http.StatusText(e.Status)})
  44. }
  45. // UnmarshalJSON implements json.Unmarshaler interface for the Error struct.
  46. func (e *Error) UnmarshalJSON(data []byte) error {
  47. var er ErrorResponse
  48. if err := json.Unmarshal(data, &er); err != nil {
  49. return err
  50. }
  51. e.Status = er.Status
  52. e.Err = fmt.Errorf(er.Message)
  53. return nil
  54. }
  55. // NewError returns a new Error. If the given error implements the StatusCoder
  56. // interface we will ignore the given status.
  57. func NewError(status int, err error) error {
  58. if sc, ok := err.(StatusCoder); ok {
  59. return &Error{Status: sc.StatusCode(), Err: err}
  60. }
  61. cause := errors.Cause(err)
  62. if sc, ok := cause.(StatusCoder); ok {
  63. return &Error{Status: sc.StatusCode(), Err: err}
  64. }
  65. return &Error{Status: status, Err: err}
  66. }
  67. // InternalServerError returns a 500 error with the given error.
  68. func InternalServerError(err error) error {
  69. return NewError(http.StatusInternalServerError, err)
  70. }
  71. // BadRequest returns an 400 error with the given error.
  72. func BadRequest(err error) error {
  73. return NewError(http.StatusBadRequest, err)
  74. }
  75. // Unauthorized returns an 401 error with the given error.
  76. func Unauthorized(err error) error {
  77. return NewError(http.StatusUnauthorized, err)
  78. }
  79. // Forbidden returns an 403 error with the given error.
  80. func Forbidden(err error) error {
  81. return NewError(http.StatusForbidden, err)
  82. }
  83. // NotFound returns an 404 error with the given error.
  84. func NotFound(err error) error {
  85. return NewError(http.StatusNotFound, err)
  86. }
  87. // WriteError writes to w a JSON representation of the given error.
  88. func WriteError(w http.ResponseWriter, err error) {
  89. w.Header().Set("Content-Type", "application/json")
  90. cause := errors.Cause(err)
  91. if sc, ok := err.(StatusCoder); ok {
  92. w.WriteHeader(sc.StatusCode())
  93. } else {
  94. if sc, ok := cause.(StatusCoder); ok {
  95. w.WriteHeader(sc.StatusCode())
  96. } else {
  97. w.WriteHeader(http.StatusInternalServerError)
  98. }
  99. }
  100. // Write errors in the response writer
  101. if rl, ok := w.(logging.ResponseLogger); ok {
  102. rl.WithFields(map[string]interface{}{
  103. "error": err,
  104. })
  105. if os.Getenv("STEPDEBUG") == "1" {
  106. if e, ok := err.(StackTracer); ok {
  107. rl.WithFields(map[string]interface{}{
  108. "stack-trace": fmt.Sprintf("%+v", e),
  109. })
  110. } else {
  111. if e, ok := cause.(StackTracer); ok {
  112. rl.WithFields(map[string]interface{}{
  113. "stack-trace": fmt.Sprintf("%+v", e),
  114. })
  115. }
  116. }
  117. }
  118. }
  119. if err := json.NewEncoder(w).Encode(err); err != nil {
  120. LogError(w, err)
  121. }
  122. }