Dawid Wysokiński
79cc49d98e
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #5
57 lines
1.2 KiB
Go
57 lines
1.2 KiB
Go
package rest
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"net/http"
|
|
|
|
"gitea.dwysokinski.me/Kichiyaki/notificationarr/internal/domain"
|
|
)
|
|
|
|
//go:generate counterfeiter -generate
|
|
|
|
var (
|
|
errInternal = domain.NewError(
|
|
domain.WithCode(domain.ErrorCodeUnknown),
|
|
domain.WithMessage("internal server error"),
|
|
)
|
|
)
|
|
|
|
type APIError struct {
|
|
Code string `json:"code"`
|
|
Message string `json:"message"`
|
|
}
|
|
type ErrorResponse struct {
|
|
Error APIError `json:"error"`
|
|
}
|
|
|
|
func renderErrorResponse(w http.ResponseWriter, err error) {
|
|
var convError domain.Error
|
|
if !errors.As(err, &convError) {
|
|
convError = errInternal
|
|
}
|
|
renderJSON(w, errorCodeToHTTPStatus(convError.Code()), ErrorResponse{
|
|
Error: APIError{
|
|
Code: convError.Code().String(),
|
|
Message: convError.Message(),
|
|
},
|
|
})
|
|
}
|
|
func errorCodeToHTTPStatus(code domain.ErrorCode) int {
|
|
switch code {
|
|
case domain.ErrorCodeValidation:
|
|
return http.StatusBadRequest
|
|
case domain.ErrorCodeIO:
|
|
return http.StatusServiceUnavailable
|
|
case domain.ErrorCodeUnknown:
|
|
fallthrough
|
|
default:
|
|
return http.StatusInternalServerError
|
|
}
|
|
}
|
|
func renderJSON(w http.ResponseWriter, status int, data interface{}) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(status)
|
|
_ = json.NewEncoder(w).Encode(data)
|
|
}
|