115 lines
4.3 KiB
Python
115 lines
4.3 KiB
Python
"""Единый формат ошибок и маппинг исключений на HTTP (docs/05 §5.3).
|
|
|
|
Тело любой ошибки: {"error": {"code", "message", "details", "trace_id"}}.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
from fastapi import Request
|
|
from fastapi.exceptions import RequestValidationError
|
|
from fastapi.responses import JSONResponse
|
|
from starlette.exceptions import HTTPException as StarletteHTTPException
|
|
|
|
from app.cv.exceptions import (
|
|
BlobInvalid,
|
|
CvError,
|
|
FormatUnsupported,
|
|
ImageDecodeFailed,
|
|
ImageFormatUnsupported,
|
|
ImageTooSmall,
|
|
InvalidSettings,
|
|
UnknownProfile,
|
|
)
|
|
|
|
# Маппинг исключений CV-ядра на коды ответов — единственная точка,
|
|
# где ядро «узнаёт» о HTTP (docs/03 §3.5-1).
|
|
_CV_ERROR_MAP: list[tuple[type[CvError], int, str]] = [
|
|
(ImageDecodeFailed, 400, "IMAGE_DECODE_FAILED"),
|
|
(ImageTooSmall, 400, "IMAGE_TOO_SMALL"),
|
|
(BlobInvalid, 400, "FEATURE_BLOB_INVALID"),
|
|
(FormatUnsupported, 400, "FEATURE_FORMAT_UNSUPPORTED"),
|
|
(UnknownProfile, 400, "UNKNOWN_PROFILE"),
|
|
(ImageFormatUnsupported, 415, "UNSUPPORTED_MEDIA_TYPE"),
|
|
(InvalidSettings, 422, "INVALID_SETTINGS"),
|
|
]
|
|
|
|
|
|
class ApiError(Exception):
|
|
"""Транспортная ошибка API-слоя с готовым кодом ответа."""
|
|
|
|
def __init__(self, status_code: int, code: str, message: str, details: dict | None = None):
|
|
super().__init__(message)
|
|
self.status_code = status_code
|
|
self.code = code
|
|
self.message = message
|
|
self.details = details or {}
|
|
|
|
|
|
def error_body(code: str, message: str, trace_id: str, details: dict | None = None) -> dict:
|
|
return {"error": {"code": code, "message": message, "details": details or {}, "trace_id": trace_id}}
|
|
|
|
|
|
def _trace_id(request: Request) -> str:
|
|
return getattr(request.state, "trace_id", "")
|
|
|
|
|
|
def install_error_handlers(app) -> None:
|
|
@app.exception_handler(ApiError)
|
|
async def _api_error(request: Request, exc: ApiError):
|
|
return JSONResponse(
|
|
status_code=exc.status_code,
|
|
content=error_body(exc.code, exc.message, _trace_id(request), exc.details),
|
|
)
|
|
|
|
@app.exception_handler(CvError)
|
|
async def _cv_error(request: Request, exc: CvError):
|
|
for exc_type, status, code in _CV_ERROR_MAP:
|
|
if isinstance(exc, exc_type):
|
|
return JSONResponse(
|
|
status_code=status,
|
|
content=error_body(code, str(exc), _trace_id(request), exc.details),
|
|
)
|
|
return JSONResponse(
|
|
status_code=500,
|
|
content=error_body("INTERNAL", "Внутренняя ошибка сервиса", _trace_id(request)),
|
|
)
|
|
|
|
@app.exception_handler(RequestValidationError)
|
|
async def _validation(request: Request, exc: RequestValidationError):
|
|
return JSONResponse(
|
|
status_code=422,
|
|
content=error_body(
|
|
"VALIDATION_ERROR", "Некорректный запрос", _trace_id(request),
|
|
{"errors": [
|
|
{"loc": [str(p) for p in e.get("loc", [])], "msg": e.get("msg", "")}
|
|
for e in exc.errors()
|
|
]},
|
|
),
|
|
)
|
|
|
|
@app.exception_handler(StarletteHTTPException)
|
|
async def _http_error(request: Request, exc: StarletteHTTPException):
|
|
code = {401: "UNAUTHORIZED", 403: "FORBIDDEN", 404: "NOT_FOUND", 405: "METHOD_NOT_ALLOWED"}.get(
|
|
exc.status_code, "HTTP_ERROR"
|
|
)
|
|
return JSONResponse(
|
|
status_code=exc.status_code,
|
|
content=error_body(code, str(exc.detail), _trace_id(request)),
|
|
headers=getattr(exc, "headers", None),
|
|
)
|
|
|
|
@app.exception_handler(Exception)
|
|
async def _unhandled(request: Request, exc: Exception):
|
|
import logging
|
|
|
|
logging.getLogger("opencv").exception(
|
|
"Необработанное исключение", extra={"fields": {"trace_id": _trace_id(request)}}
|
|
)
|
|
return JSONResponse(
|
|
status_code=500,
|
|
content=error_body(
|
|
"INTERNAL",
|
|
"Внутренняя ошибка сервиса; детали в логах по trace_id",
|
|
_trace_id(request),
|
|
),
|
|
)
|