forked from mtusi2026/mtusi2026lab4
chore(solution): port lab3 sources
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
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.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")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user