forked from mtusi2026/mtusi2026lab3
72 lines
2.1 KiB
Go
72 lines
2.1 KiB
Go
package fiber
|
|
|
|
import (
|
|
"errors"
|
|
"net/http"
|
|
|
|
"github.com/gofiber/fiber/v2"
|
|
"github.com/google/uuid"
|
|
"go.lab260.ru/fielderr"
|
|
"go.uber.org/zap"
|
|
|
|
httpmodel "gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/http"
|
|
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/service"
|
|
)
|
|
|
|
// handleErr normalizes a failure and writes the public error envelope.
|
|
func (ctrl *Controller) handleErr(ctx *fiber.Ctx, err error) error {
|
|
requestID := ctx.GetRespHeader(headerRequestID)
|
|
if requestID == "" {
|
|
requestID = uuid.NewString()
|
|
ctx.Set(headerRequestID, requestID)
|
|
}
|
|
err = publicError(normalizeTransportError(err))
|
|
status, ok := fielderr.HTTPStatusFrom(ctrl.errorRegistry, err)
|
|
if !ok {
|
|
err = errInternal
|
|
status = http.StatusInternalServerError
|
|
}
|
|
if status == http.StatusUnauthorized {
|
|
challenge := `Bearer realm="messenger"`
|
|
if ctx.Path() == "/api/v1/auth/sessions" && ctx.Method() == http.MethodPost {
|
|
challenge = `Basic realm="messenger", charset="UTF-8"`
|
|
}
|
|
ctx.Set(fiber.HeaderWWWAuthenticate, challenge)
|
|
}
|
|
if status == http.StatusInternalServerError {
|
|
ctrl.log.Error("unexpected request failure", zap.String("request_id", requestID))
|
|
}
|
|
return ctx.Status(status).JSON(errorResponse(err, requestID))
|
|
}
|
|
|
|
// normalizeTransportError maps Fiber failures to transport-independent application errors.
|
|
func normalizeTransportError(err error) error {
|
|
transportError, ok := errors.AsType[*fiber.Error](err)
|
|
if !ok {
|
|
return err
|
|
}
|
|
switch transportError.Code {
|
|
case http.StatusRequestEntityTooLarge:
|
|
return errTooLarge
|
|
case http.StatusNotFound, http.StatusMethodNotAllowed:
|
|
return service.ErrNotFound
|
|
case http.StatusBadRequest, http.StatusRequestTimeout, http.StatusRequestHeaderFieldsTooLarge:
|
|
return service.ErrInvalid
|
|
default:
|
|
return errInternal
|
|
}
|
|
}
|
|
|
|
// errorResponse builds the public error envelope with its request identifier.
|
|
func errorResponse(err error, requestID string) httpmodel.ErrorResponse {
|
|
status, _ := fielderr.Status(err)
|
|
message, _ := fielderr.PublicMessage(err)
|
|
return httpmodel.ErrorResponse{
|
|
Error: httpmodel.ErrorDetail{
|
|
Code: status.String(),
|
|
Message: message,
|
|
RequestID: requestID,
|
|
},
|
|
}
|
|
}
|