errors.go 2.1 KB

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