Implement exception handler

This commit is contained in:
Iam54r1n4
2025-02-03 19:05:04 +00:00
parent 9d42e56f47
commit d0a73a6fc6
2 changed files with 21 additions and 0 deletions

View File

@ -0,0 +1,20 @@
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse
from pydantic import BaseModel
class JSONErrorResponse(BaseModel):
status: int
detail: str
def setup_exception_handler(app: FastAPI):
'''
Setup exception handler for FastAPI.
'''
@app.exception_handler(Exception)
async def http_exception_handler(request: Request, exc: HTTPException): # type: ignore
return JSONResponse(
status_code=exc.status_code,
content=JSONErrorResponse(status=exc.status_code, detail=exc.detail).model_dump(),
)