File size: 3,222 Bytes
9766e10 | 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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 | from fastapi import Request, Response
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException
from fastapi.utils import is_body_allowed_for_status_code
from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY
from app.core.constants import (
REQUEST_ID_HEADER,
SECURITY_HEADERS,
CSP_HEADER
)
import logging
logger = logging.getLogger(__name__)
async def http_exception_handler(
request: Request,
exception: HTTPException
) -> Response:
headers = getattr(exception, "headers", None) or {}
request_id = getattr(request.state, "request_id", 'not-set')
logger.warning(
"http_exception",
extra={
"path": request.url.path,
"status_code": exception.status_code,
"request_id": request_id,
"method": request.method,
"error_type": type(exception).__name__,
"error": str(exception.detail),
},
)
if not is_body_allowed_for_status_code(exception.status_code):
return Response(status_code=exception.status_code, headers=headers)
return JSONResponse(
status_code=exception.status_code,
content={
"detail": exception.detail,
"request_id": request_id,
},
headers= headers | {
REQUEST_ID_HEADER: request_id,
**SECURITY_HEADERS,
**CSP_HEADER
}
)
async def request_validation_error_handler(
request: Request,
exception: RequestValidationError
) -> Response:
headers = getattr(exception, "headers", None) or {}
request_id = getattr(request.state, "request_id", 'not-set')
logger.warning(
"request_validation_exception",
extra={
"path": request.url.path,
"request_id": request_id,
"method": request.method,
"error_type": type(exception).__name__,
"error": str(exception.errors())
},
)
return JSONResponse(
status_code=HTTP_422_UNPROCESSABLE_ENTITY,
content={
"detail": jsonable_encoder(exception.errors()),
"request_id": request_id,
},
headers= headers | {
REQUEST_ID_HEADER: request_id,
**SECURITY_HEADERS,
**CSP_HEADER
}
)
async def global_exception_handler(
request: Request,
exception: Exception
) -> Response:
headers = getattr(exception, "headers", None) or {}
request_id = getattr(request.state, "request_id", 'not-set')
logger.exception(
"unhandled_exception",
extra={
"path": request.url.path,
"request_id": request_id,
"method": request.method,
"error_type": type(exception).__name__
},
)
return JSONResponse(
status_code=500,
content={
"detail": "Internal Server Error",
"request_id": request_id,
},
headers=headers | {
REQUEST_ID_HEADER: request_id,
**SECURITY_HEADERS,
**CSP_HEADER
}
) |