errors.go 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. package api
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "os"
  7. "github.com/pkg/errors"
  8. "github.com/smallstep/certificates/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. // NotImplemented returns a 500 error with the given error.
  72. func NotImplemented(err error) error {
  73. return NewError(http.StatusNotImplemented, err)
  74. }
  75. // BadRequest returns an 400 error with the given error.
  76. func BadRequest(err error) error {
  77. return NewError(http.StatusBadRequest, err)
  78. }
  79. // Unauthorized returns an 401 error with the given error.
  80. func Unauthorized(err error) error {
  81. return NewError(http.StatusUnauthorized, err)
  82. }
  83. // Forbidden returns an 403 error with the given error.
  84. func Forbidden(err error) error {
  85. return NewError(http.StatusForbidden, err)
  86. }
  87. // NotFound returns an 404 error with the given error.
  88. func NotFound(err error) error {
  89. return NewError(http.StatusNotFound, err)
  90. }
  91. // WriteError writes to w a JSON representation of the given error.
  92. func WriteError(w http.ResponseWriter, err error) {
  93. w.Header().Set("Content-Type", "application/json")
  94. cause := errors.Cause(err)
  95. if sc, ok := err.(StatusCoder); ok {
  96. w.WriteHeader(sc.StatusCode())
  97. } else {
  98. if sc, ok := cause.(StatusCoder); ok {
  99. w.WriteHeader(sc.StatusCode())
  100. } else {
  101. w.WriteHeader(http.StatusInternalServerError)
  102. }
  103. }
  104. // Write errors in the response writer
  105. if rl, ok := w.(logging.ResponseLogger); ok {
  106. rl.WithFields(map[string]interface{}{
  107. "error": err,
  108. })
  109. if os.Getenv("STEPDEBUG") == "1" {
  110. if e, ok := err.(StackTracer); ok {
  111. rl.WithFields(map[string]interface{}{
  112. "stack-trace": fmt.Sprintf("%+v", e),
  113. })
  114. } else {
  115. if e, ok := cause.(StackTracer); ok {
  116. rl.WithFields(map[string]interface{}{
  117. "stack-trace": fmt.Sprintf("%+v", e),
  118. })
  119. }
  120. }
  121. }
  122. }
  123. if err := json.NewEncoder(w).Encode(err); err != nil {
  124. LogError(w, err)
  125. }
  126. }