api_errors.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package errors
  2. import (
  3. "net/http"
  4. "github.com/gravitl/netmaker/models"
  5. )
  6. type ApiRespErr string
  7. const (
  8. Internal ApiRespErr = "internal"
  9. BadRequest ApiRespErr = "badrequest"
  10. NotFound ApiRespErr = "notfound"
  11. UnAuthorized ApiRespErr = "unauthorized"
  12. Forbidden ApiRespErr = "forbidden"
  13. Unavailable ApiRespErr = "unavailable"
  14. )
  15. // FormatError - formats into api error resp
  16. func FormatError(err error, errType ApiRespErr) models.ErrorResponse {
  17. var status = http.StatusInternalServerError
  18. switch errType {
  19. case Internal:
  20. status = http.StatusInternalServerError
  21. case BadRequest:
  22. status = http.StatusBadRequest
  23. case NotFound:
  24. status = http.StatusNotFound
  25. case UnAuthorized:
  26. status = http.StatusUnauthorized
  27. case Forbidden:
  28. status = http.StatusForbidden
  29. case Unavailable:
  30. status = http.StatusServiceUnavailable
  31. default:
  32. status = http.StatusInternalServerError
  33. }
  34. var response = models.ErrorResponse{
  35. Code: status,
  36. }
  37. if err != nil {
  38. response.Message = err.Error()
  39. }
  40. return response
  41. }