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 ) from app.core.context import request_id_ctx 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 } )