Files
mtusi2026lab4-implementation/internal/handler/errors.go
T

60 lines
2.0 KiB
Go

package handler
import (
"errors"
"net/http"
"messenger/internal/domain"
)
type apiError struct {
status int
code string
message string
}
func (e *apiError) Error() string { return e.message }
func badRequest(msg string) *apiError {
return &apiError{http.StatusBadRequest, "invalid_request", msg}
}
func writeError(w http.ResponseWriter, status int, code, message string) {
writeJSON(w, status, errorBody{Error: errorDetails{
Code: code,
Message: message,
RequestID: w.Header().Get(headerRequestID),
}})
}
func (h *Handler) fail(w http.ResponseWriter, r *http.Request, err error) {
var ae *apiError
switch {
case errors.As(err, &ae):
writeError(w, ae.status, ae.code, ae.message)
case errors.Is(err, domain.ErrInvalidInput):
writeError(w, http.StatusBadRequest, "invalid_request", err.Error())
case errors.Is(err, domain.ErrUnauthorized):
if w.Header().Get(headerWWWAuthenticate) == "" {
w.Header().Set(headerWWWAuthenticate, bearerChallenge)
}
writeError(w, http.StatusUnauthorized, "unauthorized", "valid authentication is required")
case errors.Is(err, domain.ErrNotFound):
writeError(w, http.StatusNotFound, "not_found", "resource not found")
case errors.Is(err, domain.ErrConflict):
writeError(w, http.StatusConflict, "conflict", err.Error())
case errors.Is(err, domain.ErrTooLarge):
writeError(w, http.StatusRequestEntityTooLarge, "payload_too_large", err.Error())
case errors.Is(err, domain.ErrUnsupportedMedia):
writeError(w, http.StatusUnsupportedMediaType, "unsupported_media_type", err.Error())
case errors.Is(err, domain.ErrUnavailable):
h.log.Error("dependency unavailable", "request_id", w.Header().Get(headerRequestID),
"method", r.Method, "path", r.URL.Path, "err", err)
writeError(w, http.StatusServiceUnavailable, "unavailable", "service temporarily unavailable")
default:
h.log.Error("unexpected error", "request_id", w.Header().Get(headerRequestID),
"method", r.Method, "path", r.URL.Path, "err", err)
writeError(w, http.StatusInternalServerError, "internal_error", "internal server error")
}
}