feat: exception and error middleware (#2590)
exception and error middleware
This commit is contained in:
parent
4c43b4cc82
commit
ce9b4b09e5
1 changed files with 18 additions and 2 deletions
|
|
@ -7,10 +7,11 @@ from typing import Optional
|
|||
from urllib.parse import urlencode
|
||||
|
||||
import nest_asyncio # type: ignore
|
||||
from fastapi import FastAPI, Request, Response
|
||||
from fastapi import FastAPI, Request, Response, HTTPException
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import FileResponse
|
||||
from fastapi.responses import FileResponse, JSONResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from http import HTTPStatus
|
||||
from loguru import logger
|
||||
from pydantic import PydanticDeprecatedSince20
|
||||
from rich import print as rprint
|
||||
|
|
@ -158,6 +159,21 @@ def create_app():
|
|||
app.include_router(router)
|
||||
app.include_router(health_check_router)
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def exception_handler(request: Request, exc: Exception):
|
||||
if isinstance(exc, HTTPException):
|
||||
logger.error(f"HTTPException: {exc.detail}")
|
||||
return JSONResponse(
|
||||
status_code=exc.status_code,
|
||||
content={"message": str(exc.detail)},
|
||||
)
|
||||
else:
|
||||
logger.error(f"unhandled error: {exc}")
|
||||
return JSONResponse(
|
||||
status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
|
||||
content={"message": str(exc)},
|
||||
)
|
||||
|
||||
FastAPIInstrumentor.instrument_app(app)
|
||||
|
||||
return app
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue