
- Set up project structure and dependencies - Create task model and schema - Implement Alembic migrations - Add CRUD API endpoints for task management - Add health endpoint with database connectivity check - Add comprehensive error handling - Add tests for API endpoints - Update README with API documentation
62 lines
1.9 KiB
Python
62 lines
1.9 KiB
Python
from fastapi import HTTPException, Request, status
|
|
from fastapi.exceptions import RequestValidationError
|
|
from fastapi.responses import JSONResponse
|
|
from starlette.exceptions import HTTPException as StarletteHTTPException
|
|
|
|
from app.core.config import settings
|
|
|
|
|
|
async def http_exception_handler(request: Request, exc: HTTPException) -> JSONResponse:
|
|
"""
|
|
Handle HTTPExceptions and return a consistent response format.
|
|
"""
|
|
return JSONResponse(
|
|
status_code=exc.status_code,
|
|
content={
|
|
"success": False,
|
|
"message": exc.detail,
|
|
"data": None,
|
|
},
|
|
)
|
|
|
|
|
|
async def validation_exception_handler(request: Request, exc: RequestValidationError) -> JSONResponse:
|
|
"""
|
|
Handle validation errors and return a consistent response format.
|
|
"""
|
|
return JSONResponse(
|
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
|
content={
|
|
"success": False,
|
|
"message": "Validation error",
|
|
"data": None,
|
|
"errors": exc.errors(),
|
|
},
|
|
)
|
|
|
|
|
|
async def unexpected_exception_handler(request: Request, exc: Exception) -> JSONResponse:
|
|
"""
|
|
Handle all other exceptions with a generic 500 error.
|
|
"""
|
|
return JSONResponse(
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
content={
|
|
"success": False,
|
|
"message": "Internal server error",
|
|
"data": None,
|
|
},
|
|
)
|
|
|
|
|
|
def register_exception_handlers(app):
|
|
"""
|
|
Register exception handlers with the FastAPI app.
|
|
"""
|
|
app.add_exception_handler(StarletteHTTPException, http_exception_handler)
|
|
app.add_exception_handler(HTTPException, http_exception_handler)
|
|
app.add_exception_handler(RequestValidationError, validation_exception_handler)
|
|
|
|
# Only register generic handler in production
|
|
if not settings.DEBUG:
|
|
app.add_exception_handler(Exception, unexpected_exception_handler) |