lab2
This commit is contained in:
@@ -10,7 +10,7 @@ import (
|
||||
"github.com/ogen-go/ogen/ogenerrors"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/transport/rest/oas"
|
||||
"mtusi-messenger/internal/transport/rest/internal/oas"
|
||||
)
|
||||
|
||||
var fallbackErrorBody = []byte(`{"error":{"code":"internal_error","message":"Internal error","request_id":""}}`)
|
||||
@@ -28,21 +28,38 @@ func newErrorHandler(log *slog.Logger) oas.ErrorHandler {
|
||||
}
|
||||
|
||||
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):
|
||||
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):
|
||||
case errors.Is(err, domain.ErrUsernameTaken),
|
||||
errors.Is(err, domain.ErrConflict):
|
||||
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
|
||||
}
|
||||
@@ -85,6 +102,13 @@ func writeError(ctx context.Context, log *slog.Logger, w http.ResponseWriter, r
|
||||
|
||||
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 {
|
||||
|
||||
Reference in New Issue
Block a user