142 lines
4.0 KiB
Go
142 lines
4.0 KiB
Go
package rest
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"log/slog"
|
|
"net/http"
|
|
|
|
"github.com/ogen-go/ogen/ogenerrors"
|
|
|
|
"mtusi-messenger/internal/domain"
|
|
"mtusi-messenger/internal/transport/rest/internal/oas"
|
|
)
|
|
|
|
var fallbackErrorBody = []byte(`{"error":{"code":"internal_error","message":"Internal error","request_id":""}}`)
|
|
|
|
func newErrorHandler(log *slog.Logger) oas.ErrorHandler {
|
|
return func(ctx context.Context, w http.ResponseWriter, r *http.Request, err error) {
|
|
status := statusForError(err)
|
|
|
|
if preMiddlewareError(err) {
|
|
logRejected(ctx, log, r, status, err)
|
|
}
|
|
|
|
writeError(ctx, log, w, r, status)
|
|
}
|
|
}
|
|
|
|
func statusForError(err error) int {
|
|
var securityErr *ogenerrors.SecurityError
|
|
|
|
if errors.As(err, &securityErr) {
|
|
if status := statusForDomainError(securityErr.Err); status != http.StatusInternalServerError {
|
|
return status
|
|
}
|
|
|
|
return http.StatusUnauthorized
|
|
}
|
|
|
|
if status := ogenerrors.ErrorCode(err); status != http.StatusInternalServerError {
|
|
return status
|
|
}
|
|
|
|
return statusForDomainError(err)
|
|
}
|
|
|
|
func statusForDomainError(err error) int {
|
|
switch {
|
|
case errors.Is(err, ErrUnauthenticated), errors.Is(err, domain.ErrUnauthenticated):
|
|
return http.StatusUnauthorized
|
|
case errors.Is(err, domain.ErrNotFound):
|
|
return http.StatusNotFound
|
|
case errors.Is(err, domain.ErrUsernameTaken),
|
|
errors.Is(err, domain.ErrConflict),
|
|
errors.Is(err, domain.ErrIdempotency):
|
|
return http.StatusConflict
|
|
case errors.Is(err, domain.ErrValidation),
|
|
errors.Is(err, domain.ErrUnknownMember),
|
|
errors.Is(err, domain.ErrInvalidCursor):
|
|
return http.StatusBadRequest
|
|
case errors.Is(err, domain.ErrUnavailable):
|
|
return http.StatusServiceUnavailable
|
|
default:
|
|
return http.StatusInternalServerError
|
|
}
|
|
}
|
|
|
|
func newNotFoundHandler(log *slog.Logger) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
logRejected(r.Context(), log, r, http.StatusNotFound, nil)
|
|
writeError(r.Context(), log, w, r, http.StatusNotFound)
|
|
}
|
|
}
|
|
|
|
func newMethodNotAllowedHandler(log *slog.Logger) func(http.ResponseWriter, *http.Request, string) {
|
|
return func(w http.ResponseWriter, r *http.Request, allowed string) {
|
|
w.Header().Set("Allow", allowed)
|
|
logRejected(r.Context(), log, r, http.StatusMethodNotAllowed, nil)
|
|
writeError(r.Context(), log, w, r, http.StatusMethodNotAllowed)
|
|
}
|
|
}
|
|
|
|
func writeError(ctx context.Context, log *slog.Logger, w http.ResponseWriter, r *http.Request, status int) {
|
|
requestID := requestIDFromContext(ctx)
|
|
if requestID == "" {
|
|
requestID = r.Header.Get(requestIDHeader)
|
|
}
|
|
|
|
body := oas.Error{
|
|
Error: oas.ErrorError{
|
|
Code: codeForStatus(status),
|
|
Message: http.StatusText(status),
|
|
RequestID: requestID,
|
|
},
|
|
}
|
|
|
|
payload, marshalErr := json.Marshal(body)
|
|
if marshalErr != nil {
|
|
status = http.StatusInternalServerError
|
|
payload = fallbackErrorBody
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
w.Header().Set(requestIDHeader, requestID)
|
|
if status == http.StatusUnauthorized {
|
|
challenge := `Bearer realm="messenger"`
|
|
if r.URL.Path == "/api/v1/auth/sessions" {
|
|
challenge = `Basic realm="messenger", charset="UTF-8"`
|
|
}
|
|
w.Header().Set("WWW-Authenticate", challenge)
|
|
}
|
|
w.WriteHeader(status)
|
|
|
|
if _, err := w.Write(payload); err != nil && log != nil {
|
|
log.WarnContext(ctx, "response write failed", slog.String("error", err.Error()))
|
|
}
|
|
}
|
|
|
|
func codeForStatus(status int) oas.ErrorErrorCode {
|
|
switch status {
|
|
case http.StatusBadRequest, http.StatusMethodNotAllowed:
|
|
return oas.ErrorErrorCodeInvalidRequest
|
|
case http.StatusUnauthorized:
|
|
return oas.ErrorErrorCodeUnauthorized
|
|
case http.StatusNotFound:
|
|
return oas.ErrorErrorCodeNotFound
|
|
case http.StatusConflict:
|
|
return oas.ErrorErrorCodeConflict
|
|
case http.StatusRequestEntityTooLarge:
|
|
return oas.ErrorErrorCodePayloadTooLarge
|
|
case http.StatusUnsupportedMediaType:
|
|
return oas.ErrorErrorCodeUnsupportedMediaType
|
|
case http.StatusTooManyRequests:
|
|
return oas.ErrorErrorCodeRateLimited
|
|
case http.StatusServiceUnavailable:
|
|
return oas.ErrorErrorCodeUnavailable
|
|
default:
|
|
return oas.ErrorErrorCodeInternalError
|
|
}
|
|
}
|