52 lines
1.5 KiB
Python
52 lines
1.5 KiB
Python
"""Custom exception handlers."""
|
|
|
|
from fastapi import Request, status
|
|
from fastapi.responses import JSONResponse
|
|
from fastapi.exceptions import RequestValidationError
|
|
from pydantic import ValidationError
|
|
from app.core.exceptions import AppException
|
|
|
|
|
|
async def app_exception_handler(request: Request, exc: Exception):
|
|
"""Handle all unhandled exceptions."""
|
|
if isinstance(exc, AppException):
|
|
return JSONResponse(
|
|
status_code=exc.status_code,
|
|
content={
|
|
"message": exc.message,
|
|
"error_code": exc.error_code,
|
|
"success": False
|
|
}
|
|
)
|
|
return JSONResponse(
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
content={
|
|
"message": "Internal server error",
|
|
"success": False
|
|
}
|
|
)
|
|
|
|
|
|
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
|
"""Handle validation errors."""
|
|
return JSONResponse(
|
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
|
content={
|
|
"message": "Validation error",
|
|
"errors": exc.errors(),
|
|
"success": False
|
|
}
|
|
)
|
|
|
|
|
|
async def pydantic_validation_exception_handler(request: Request, exc: ValidationError):
|
|
"""Handle Pydantic validation errors."""
|
|
return JSONResponse(
|
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
|
content={
|
|
"message": "Validation error",
|
|
"errors": exc.errors(),
|
|
"success": False
|
|
}
|
|
)
|