Files
mtusi2026lab5/backend/internal/adapter/handler/errors.go
T

86 lines
3.9 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package handler
import (
"encoding/json"
"errors"
"net/http"
"backend/internal/domain/model"
)
var (
errRouteNotFound = errors.New("route not found")
errMethodNotAllowed = errors.New("method not allowed")
errPayloadTooLarge = errors.New("payload too large")
errOverloaded = errors.New("overloaded")
errDraining = errors.New("draining")
errUnsupportedImage = errors.New("unsupported image")
)
type apiError struct {
status int
code ErrorErrorCode
message string
}
// classify — единственное место, где ошибка превращается в HTTP-статус.
func classify(err error) apiError {
var invalid *model.ValidationError
switch {
case errors.As(err, &invalid):
return apiError{http.StatusBadRequest, InvalidRequest, invalid.Message}
case errors.Is(err, model.ErrUnauthorized):
return apiError{http.StatusUnauthorized, Unauthorized, "нужна действующая сессия"}
case errors.Is(err, model.ErrNotFound), errors.Is(err, errRouteNotFound):
return apiError{http.StatusNotFound, NotFound, "объект не найден"}
case errors.Is(err, errMethodNotAllowed):
return apiError{http.StatusMethodNotAllowed, InvalidRequest, "метод не поддерживается"}
case errors.Is(err, model.ErrUsernameTaken):
return apiError{http.StatusConflict, Conflict, "username уже занят"}
case errors.Is(err, model.ErrConflict):
return apiError{http.StatusConflict, Conflict, "конфликт запроса"}
case errors.Is(err, model.ErrUnavailable):
return apiError{http.StatusServiceUnavailable, Unavailable, "зависимость недоступна"}
case errors.Is(err, errPayloadTooLarge):
return apiError{http.StatusRequestEntityTooLarge, PayloadTooLarge, "тело запроса больше допустимого"}
case errors.Is(err, errUnsupportedImage):
return apiError{http.StatusUnsupportedMediaType, UnsupportedMediaType, "нужен корректный PNG или JPEG с верным Content-Type"}
case errors.Is(err, model.ErrStorageFull):
return apiError{http.StatusServiceUnavailable, Unavailable, "хранилище заполнено, запись невозможна; чтение работает"}
case errors.Is(err, errOverloaded):
return apiError{http.StatusServiceUnavailable, Unavailable, "сервер перегружен, повторите позже"}
case errors.Is(err, errDraining):
return apiError{http.StatusServiceUnavailable, Unavailable, "сервер останавливается"}
default:
return apiError{http.StatusInternalServerError, InternalError, "внутренняя ошибка"}
}
}
func (h *API) writeError(w http.ResponseWriter, r *http.Request, err error) {
e := classify(err)
if e.status == http.StatusInternalServerError {
h.log.Error().Err(err).Str("request_id", requestIDFrom(r.Context())).Msg("unexpected error")
}
if errors.Is(err, errOverloaded) {
w.Header().Set("Retry-After", "1")
}
var body Error
body.Error.Code = e.code
body.Error.Message = e.message
body.Error.RequestId = requestIDFrom(r.Context())
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(e.status)
_ = json.NewEncoder(w).Encode(body)
}
// bodyError — JSON синтаксически верен (это проверил jsonBody), но не
// подходит к схеме: лишнее поле или неверный тип.
func (h *API) bodyError(w http.ResponseWriter, r *http.Request, _ error) {
h.writeError(w, r, &model.ValidationError{Message: "тело запроса не соответствует схеме: лишнее поле или неверный тип"})
}
// paramError — path или query параметр не разобрался (UUID, целое число).
func (h *API) paramError(w http.ResponseWriter, r *http.Request, _ error) {
h.writeError(w, r, &model.ValidationError{Message: "некорректный параметр запроса"})
}