Desi-Clans/backend/app/core/errors.py
2026-10-08 02:52:58 +05:30

23 lines
932 B
Python

from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
class AppError(Exception):
"""Application-level error mapped to an HTTP response."""
def __init__(self, message: str, status_code: int = 400) -> None:
self.message = message
self.status_code = status_code
super().__init__(message)
def register_exception_handlers(app: FastAPI) -> None:
@app.exception_handler(AppError)
async def handle_app_error(_request: Request, exc: AppError) -> JSONResponse:
return JSONResponse(status_code=exc.status_code, content={"detail": exc.message})
@app.exception_handler(Exception)
async def handle_unexpected_error(_request: Request, exc: Exception) -> JSONResponse:
if app.debug:
return JSONResponse(status_code=500, content={"detail": str(exc)})
return JSONResponse(status_code=500, content={"detail": "Internal server error"})