netmaker/logic/errors.go

59 lines
1.7 KiB
Go
Raw Normal View History

2022-09-15 01:26:31 +08:00
package logic
2021-04-13 11:19:01 +08:00
import (
2021-04-23 04:52:44 +08:00
"encoding/json"
"net/http"
2021-12-07 04:31:08 +08:00
"github.com/gravitl/netmaker/logger"
2021-04-23 04:52:44 +08:00
"github.com/gravitl/netmaker/models"
2021-04-13 11:19:01 +08:00
)
2022-09-15 01:26:31 +08:00
// FormatError - takes ErrorResponse and uses correct code
func FormatError(err error, errType string) models.ErrorResponse {
2021-04-13 11:19:01 +08:00
var status = http.StatusInternalServerError
switch errType {
case "internal":
status = http.StatusInternalServerError
case "badrequest":
2021-04-23 04:52:44 +08:00
status = http.StatusBadRequest
2021-04-13 11:19:01 +08:00
case "notfound":
status = http.StatusNotFound
case "unauthorized":
status = http.StatusUnauthorized
case "forbidden":
status = http.StatusForbidden
default:
status = http.StatusInternalServerError
}
2021-04-23 04:52:44 +08:00
var response = models.ErrorResponse{
Message: err.Error(),
Code: status,
}
2021-04-13 11:19:01 +08:00
return response
}
2022-09-15 01:26:31 +08:00
// ReturnSuccessResponse - processes message and adds header
func ReturnSuccessResponse(response http.ResponseWriter, request *http.Request, message string) {
2021-04-23 04:52:44 +08:00
var httpResponse models.SuccessResponse
httpResponse.Code = http.StatusOK
httpResponse.Message = message
response.Header().Set("Content-Type", "application/json")
response.WriteHeader(http.StatusOK)
json.NewEncoder(response).Encode(httpResponse)
2021-04-13 11:19:01 +08:00
}
2022-09-15 01:26:31 +08:00
// ReturnErrorResponse - processes error and adds header
func ReturnErrorResponse(response http.ResponseWriter, request *http.Request, errorMessage models.ErrorResponse) {
2021-04-23 04:52:44 +08:00
httpResponse := &models.ErrorResponse{Code: errorMessage.Code, Message: errorMessage.Message}
jsonResponse, err := json.Marshal(httpResponse)
if err != nil {
panic(err)
}
2021-12-07 04:31:08 +08:00
logger.Log(1, "processed request error:", errorMessage.Message)
2021-04-23 04:52:44 +08:00
response.Header().Set("Content-Type", "application/json")
response.WriteHeader(errorMessage.Code)
response.Write(jsonResponse)
2021-04-13 11:19:01 +08:00
}