Files
mtusi2026lab3/app/api/errors.py
T

97 lines
3.6 KiB
Python

import logging
from fastapi import FastAPI
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from sqlalchemy.exc import SQLAlchemyError
from starlette.exceptions import HTTPException as StarletteHTTPException
from ..domain.errors import Conflict, DomainError, Invalid, NotFound, Unauthorized, Unavailable
logger = logging.getLogger('app.error')
CODE_BY_STATUS = {
400: 'invalid_request',
401: 'unauthorized',
404: 'not_found',
409: 'conflict',
413: 'payload_too_large',
415: 'unsupported_media_type',
429: 'rate_limited',
500: 'internal_error',
503: 'unavailable',
}
STATUS_BY_DOMAIN = {
Invalid: 400,
Unauthorized: 401,
NotFound: 404,
Conflict: 409,
Unavailable: 503,
}
def code_for(status: int) -> str:
if status in CODE_BY_STATUS:
return CODE_BY_STATUS[status]
return 'invalid_request' if status < 500 else 'internal_error'
def error_response(status: int, message: str, request_id: str, code: str = '') -> JSONResponse:
return JSONResponse(
status_code=status,
content={'error': {'code': code or code_for(status), 'message': message, 'request_id': request_id}},
)
def _domain_status(error: DomainError) -> int:
for kind, status in STATUS_BY_DOMAIN.items():
if isinstance(error, kind):
return status
return 500
def _describe(error: RequestValidationError) -> str:
"""Краткое указание на пол, без stack trace и внутреннего устройства"""
for item in error.errors():
if item.get('type') == 'json_invalid':
return 'тело запроса не является корректным JSON'
location = '.'.join(str(part) for part in item.get('loc', ()) if part != 'body')
return f'некорректное поле {location}' if location else 'некорректный запрос'
return 'некорректный запрос'
def request_id(request) -> str:
return getattr(request.state, 'request_id', 'unknown')
def install(app: FastAPI) -> None:
@app.exception_handler(DomainError)
async def _on_domain(request, error: DomainError) -> JSONResponse:
return error_response(_domain_status(error), error.message, request_id(request))
@app.exception_handler(RequestValidationError)
async def _on_validation(request, error: RequestValidationError) -> JSONResponse:
return error_response(400, _describe(error), request_id(request))
@app.exception_handler(SQLAlchemyError)
async def _on_database(request, error: SQLAlchemyError) -> JSONResponse:
logger.warning('database error request_id=%s type=%s', request_id(request), type(error).__name__)
return error_response(503, 'база данных недоступна', request_id(request))
@app.exception_handler(OSError)
async def _on_storage_socket(request, error: OSError) -> JSONResponse:
logger.warning('storage socket error request_id=%s type=%s', request_id(request), type(error).__name__)
return error_response(503, 'обязательное хранилище недоступно', request_id(request))
@app.exception_handler(StarletteHTTPException)
async def _on_http(request, error: StarletteHTTPException) -> JSONResponse:
message = error.detail if isinstance(error.detail, str) and error.detail else 'ошибка запроса'
response = error_response(error.status_code, message, request_id(request))
for name, value in (error.headers or {}).items():
response.headers[name] = value
return response
__all__ = ['code_for', 'error_response', 'install']