errorapi.go 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package api
  2. import (
  3. "net/http"
  4. "github.com/go-chi/render"
  5. )
  6. // ErrResponse renderer type for handling all sorts of errors.
  7. type ErrResponse struct {
  8. Err error `json:"-"` // low-level runtime error
  9. HTTPStatusCode int `json:"-"` // http response status code
  10. StatusText string `json:"status"` // user-level status message
  11. AppCode int64 `json:"code,omitempty"` // application-specific error code
  12. ErrorText string `json:"error,omitempty"` // application-level error message, for debugging
  13. }
  14. //Render render the error automaticaly to the response
  15. func (e *ErrResponse) Render(w http.ResponseWriter, r *http.Request) error {
  16. render.Status(r, e.HTTPStatusCode)
  17. return nil
  18. }
  19. //ErrInvalidRequest creates a new Invalid request error response
  20. func ErrInvalidRequest(err error) render.Renderer {
  21. return &ErrResponse{
  22. Err: err,
  23. HTTPStatusCode: http.StatusBadRequest,
  24. StatusText: "Invalid request.",
  25. ErrorText: err.Error(),
  26. }
  27. }
  28. //ErrRender creates a wrapper for any error when an output can not be rendered
  29. func ErrRender(err error) render.Renderer {
  30. return &ErrResponse{
  31. Err: err,
  32. HTTPStatusCode: http.StatusUnprocessableEntity,
  33. StatusText: "Error rendering response.",
  34. ErrorText: err.Error(),
  35. }
  36. }
  37. //ErrInternalServer render a internal server error, with another error as source
  38. func ErrInternalServer(err error) render.Renderer {
  39. return &ErrResponse{
  40. Err: err,
  41. HTTPStatusCode: http.StatusInternalServerError,
  42. StatusText: "Internal server error.",
  43. ErrorText: err.Error(),
  44. }
  45. }
  46. //ErrValidationError error on validating objects
  47. func ErrValidationError(err error) render.Renderer {
  48. return &ErrResponse{
  49. Err: err,
  50. HTTPStatusCode: http.StatusBadRequest,
  51. StatusText: "Validation error.",
  52. ErrorText: err.Error(),
  53. }
  54. }
  55. //ErrNotFound requested resource was not found
  56. var ErrNotFound = &ErrResponse{HTTPStatusCode: http.StatusNotFound, StatusText: "Resource not found."}
  57. //ErrNotImplemted this feature/function/methode is not implemented yet
  58. var ErrNotImplemted = &ErrResponse{HTTPStatusCode: http.StatusNotImplemented, StatusText: "Not im plemented yet."}
  59. //ErrUniqueIndexError index violation error
  60. var ErrUniqueIndexError = &ErrResponse{HTTPStatusCode: http.StatusBadRequest, StatusText: "Unique index violation."}
  61. //ErrForbidden not enough rights for doing this
  62. var ErrForbidden = &ErrResponse{HTTPStatusCode: http.StatusForbidden, StatusText: "endpoint not permitted."}