File size: 884 Bytes
76faade
 
 
 
 
 
 
 
fc6c25b
76faade
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import logging

from fastapi import FastAPI, HTTPException, Request, status
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse

logger = logging.getLogger(__name__)


def init_error_handlers(app: FastAPI):
    @app.exception_handler(Exception)
    async def exception_handler(request: Request, e: Exception):
        logger.error(f"Error during request: {e}", exc_info=e)
        return JSONResponse(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            content=jsonable_encoder({"error": str(e)}),
        )

    @app.exception_handler(HTTPException)
    async def http_exception_handler(request: Request, e: HTTPException):
        logger.error(f"Error during request: {e}", exc_info=e)
        return JSONResponse(
            status_code=e.status_code,
            content=jsonable_encoder({"error": str(e)}),
        )