This repository has been archived on 2023-04-18. You can view files and clone it, but cannot push or open issues or pull requests.
notificationarr/internal/rest/rest.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)
}