"""FastApi error handlers.""" import logging from fastapi import status from fastapi.exceptions import HTTPException from fastapi.requests import Request from fastapi.responses import JSONResponse, Response logger = logging.getLogger(__name__) DEFAULT_ERROR_MSG = ( "The server encountered an internal error and was unable to complete your request." ) def default_error_handler(_request: Request, exc: Exception) -> Response: """Handle error when uncaught exception is raised. Default exception handler Args: _request: fastapi.Request (required by FastAPI protocol, not used directly) exc: Exception object with error and trace info Returns: Response: A 500 response with JSON 'code' & 'message' payload. """ logger.exception(exc) return JSONResponse( content={ "code": "internal_error", "message": DEFAULT_ERROR_MSG, }, status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, ) def http_error_handler(_request: Request, exc: HTTPException) -> Response: """Handle error when HTTPException exception is raised. Default exception handler Args: _request: fastapi.Request (required by FastAPI protocol, not used directly) exc: Exception object with error and trace info Returns: Response: A 4xx response with JSON 'code' & 'message' payload. """ logger.info(exc.detail, extra={"code": exc.status_code}) return JSONResponse( content={ "code": "bad_request", "message": exc.detail, }, status_code=exc.status_code, )