/
httperrors.go
46 lines (39 loc) · 1.31 KB
/
httperrors.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package httperrors
import (
"net/http"
"github.com/kyma-project/kyma/components/application-registry/internal/apperrors"
)
type ErrorResponse struct {
Code int `json:"code"`
Error string `json:"error"`
}
func AppErrorToResponse(appError apperrors.AppError, detailedErrorResponse bool) (status int, body ErrorResponse) {
httpCode := errorCodeToHttpStatus(appError.Code())
errorMessage := appError.Error()
return formatErrorResponse(httpCode, errorMessage, detailedErrorResponse)
}
func errorCodeToHttpStatus(code int) int {
switch code {
case apperrors.CodeInternal:
return http.StatusInternalServerError
case apperrors.CodeNotFound:
return http.StatusNotFound
case apperrors.CodeAlreadyExists:
return http.StatusConflict
case apperrors.CodeWrongInput:
return http.StatusBadRequest
case apperrors.CodeUpstreamServerCallFailed:
return http.StatusBadGateway
default:
return http.StatusInternalServerError
}
}
func formatErrorResponse(httpCode int, errorMessage string, detailedErrorResponse bool) (status int, body ErrorResponse) {
if isInternalError(httpCode) && !detailedErrorResponse {
return httpCode, ErrorResponse{httpCode, "Internal error."}
}
return httpCode, ErrorResponse{httpCode, errorMessage}
}
func isInternalError(httpCode int) bool {
return httpCode == http.StatusInternalServerError
}