44 lines
1.8 KiB
Python
44 lines
1.8 KiB
Python
from fastapi import FastAPI, HTTPException, Request, status
|
||
from fastapi.exceptions import RequestValidationError
|
||
from fastapi.responses import JSONResponse
|
||
from sqlalchemy.exc import IntegrityError, SQLAlchemyError
|
||
|
||
|
||
def register_exception_handlers(app: FastAPI) -> None:
|
||
@app.exception_handler(RequestValidationError)
|
||
async def request_validation_exception_handler(_: Request, exc: RequestValidationError):
|
||
return JSONResponse(
|
||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||
content={"detail": exc.errors()},
|
||
)
|
||
|
||
@app.exception_handler(IntegrityError)
|
||
async def integrity_error_handler(_: Request, exc: IntegrityError):
|
||
return JSONResponse(
|
||
status_code=status.HTTP_409_CONFLICT,
|
||
content={"detail": "нарушение целостности данных в БД"},
|
||
)
|
||
|
||
@app.exception_handler(SQLAlchemyError)
|
||
async def sqlalchemy_error_handler(_: Request, exc: SQLAlchemyError):
|
||
return JSONResponse(
|
||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||
content={"detail": "ошибка базы данных"},
|
||
)
|
||
|
||
@app.exception_handler(HTTPException)
|
||
async def http_exception_handler(_: Request, exc: HTTPException):
|
||
# Не ломаем существующие ответы endpoint-ов и прокидываем исходный detail.
|
||
return JSONResponse(
|
||
status_code=exc.status_code,
|
||
content={"detail": exc.detail},
|
||
headers=exc.headers,
|
||
)
|
||
|
||
@app.exception_handler(Exception)
|
||
async def unhandled_exception_handler(_: Request, exc: Exception):
|
||
return JSONResponse(
|
||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||
content={"detail": "внутренняя ошибка сервера"},
|
||
)
|