errors.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package logic
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "github.com/gravitl/netmaker/models"
  6. "golang.org/x/exp/slog"
  7. )
  8. type ApiErrorType string
  9. const (
  10. Internal ApiErrorType = "internal"
  11. BadReq ApiErrorType = "badrequest"
  12. NotFound ApiErrorType = "notfound"
  13. UnAuthorized ApiErrorType = "unauthorized"
  14. Forbidden ApiErrorType = "forbidden"
  15. )
  16. // FormatError - takes ErrorResponse and uses correct code
  17. func FormatError(err error, errType ApiErrorType) models.ErrorResponse {
  18. var status = http.StatusInternalServerError
  19. switch errType {
  20. case Internal:
  21. status = http.StatusInternalServerError
  22. case BadReq:
  23. status = http.StatusBadRequest
  24. case NotFound:
  25. status = http.StatusNotFound
  26. case UnAuthorized:
  27. status = http.StatusUnauthorized
  28. case Forbidden:
  29. status = http.StatusForbidden
  30. default:
  31. status = http.StatusInternalServerError
  32. }
  33. var response = models.ErrorResponse{
  34. Message: err.Error(),
  35. Code: status,
  36. }
  37. return response
  38. }
  39. // ReturnSuccessResponse - processes message and adds header
  40. func ReturnSuccessResponse(response http.ResponseWriter, request *http.Request, message string) {
  41. var httpResponse models.SuccessResponse
  42. httpResponse.Code = http.StatusOK
  43. httpResponse.Message = message
  44. response.Header().Set("Content-Type", "application/json")
  45. response.WriteHeader(http.StatusOK)
  46. json.NewEncoder(response).Encode(httpResponse)
  47. }
  48. // ReturnSuccessResponseWithJson - processes message and adds header
  49. func ReturnSuccessResponseWithJson(response http.ResponseWriter, request *http.Request, res interface{}, message string) {
  50. var httpResponse models.SuccessResponse
  51. httpResponse.Code = http.StatusOK
  52. httpResponse.Response = res
  53. httpResponse.Message = message
  54. response.Header().Set("Content-Type", "application/json")
  55. response.WriteHeader(http.StatusOK)
  56. json.NewEncoder(response).Encode(httpResponse)
  57. }
  58. // ReturnErrorResponse - processes error and adds header
  59. func ReturnErrorResponse(response http.ResponseWriter, request *http.Request, errorMessage models.ErrorResponse) {
  60. httpResponse := &models.ErrorResponse{Code: errorMessage.Code, Message: errorMessage.Message}
  61. jsonResponse, err := json.Marshal(httpResponse)
  62. if err != nil {
  63. panic(err)
  64. }
  65. slog.Debug("processed request error", "err", errorMessage.Message)
  66. response.Header().Set("Content-Type", "application/json")
  67. response.WriteHeader(errorMessage.Code)
  68. response.Write(jsonResponse)
  69. }