errors.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. package apierrors
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "github.com/porter-dev/porter/api/types"
  6. "github.com/porter-dev/porter/internal/logger"
  7. )
  8. type RequestError interface {
  9. Error() string
  10. ExternalError() string
  11. InternalError() string
  12. GetStatusCode() int
  13. }
  14. type ErrInternal struct {
  15. err error
  16. }
  17. func NewErrInternal(err error) RequestError {
  18. return &ErrInternal{err}
  19. }
  20. func (e *ErrInternal) Error() string {
  21. return e.err.Error()
  22. }
  23. func (e *ErrInternal) InternalError() string {
  24. return e.err.Error()
  25. }
  26. func (e *ErrInternal) ExternalError() string {
  27. return "An internal error occurred."
  28. }
  29. func (e *ErrInternal) GetStatusCode() int {
  30. return http.StatusInternalServerError
  31. }
  32. type ErrForbidden struct {
  33. err error
  34. }
  35. func NewErrForbidden(err error) RequestError {
  36. return &ErrForbidden{err}
  37. }
  38. func (e *ErrForbidden) Error() string {
  39. return e.err.Error()
  40. }
  41. func (e *ErrForbidden) InternalError() string {
  42. return e.err.Error()
  43. }
  44. func (e *ErrForbidden) ExternalError() string {
  45. return "Forbidden"
  46. }
  47. func (e *ErrForbidden) GetStatusCode() int {
  48. return http.StatusForbidden
  49. }
  50. // errors that should be passed directly, with no filter
  51. type ErrPassThroughToClient struct {
  52. err error
  53. statusCode int
  54. }
  55. func NewErrPassThroughToClient(err error, statusCode int) RequestError {
  56. return &ErrPassThroughToClient{err, statusCode}
  57. }
  58. func (e *ErrPassThroughToClient) Error() string {
  59. return e.err.Error()
  60. }
  61. func (e *ErrPassThroughToClient) InternalError() string {
  62. return e.err.Error()
  63. }
  64. func (e *ErrPassThroughToClient) ExternalError() string {
  65. return e.err.Error()
  66. }
  67. func (e *ErrPassThroughToClient) GetStatusCode() int {
  68. return e.statusCode
  69. }
  70. func HandleAPIError(
  71. w http.ResponseWriter,
  72. logger *logger.Logger,
  73. err RequestError,
  74. ) {
  75. extErrorStr := err.ExternalError()
  76. // log the internal error
  77. logger.Warn().
  78. Str("internal_error", err.InternalError()).
  79. Str("external_error", extErrorStr).
  80. Msg("")
  81. // send the external error
  82. resp := &types.ExternalError{
  83. Error: extErrorStr,
  84. }
  85. // write the status code
  86. w.WriteHeader(err.GetStatusCode())
  87. writerErr := json.NewEncoder(w).Encode(resp)
  88. if writerErr != nil {
  89. logger.Error().
  90. Err(writerErr).
  91. Msg("")
  92. }
  93. return
  94. }