From 9f341505c4c6e73cd86b3aabda3550080448f9dd Mon Sep 17 00:00:00 2001 From: VKTB <45173816+VKTB@users.noreply.github.com> Date: Thu, 18 Jan 2024 12:34:12 +0000 Subject: [PATCH] Implement custom exception handlers #6 --- ldap_jwt_auth/main.py | 37 +++++++++++++++++++++++++++++++++- ldap_jwt_auth/routers/login.py | 3 --- 2 files changed, 36 insertions(+), 4 deletions(-) diff --git a/ldap_jwt_auth/main.py b/ldap_jwt_auth/main.py index 48fa32e..1a1b06a 100644 --- a/ldap_jwt_auth/main.py +++ b/ldap_jwt_auth/main.py @@ -3,8 +3,11 @@ """ import logging -from fastapi import FastAPI +from fastapi import FastAPI, Request, status +from fastapi.exception_handlers import request_validation_exception_handler +from fastapi.exceptions import RequestValidationError from fastapi.middleware.cors import CORSMiddleware +from fastapi.responses import JSONResponse from ldap_jwt_auth.core.config import config from ldap_jwt_auth.core.logger_setup import setup_logger @@ -16,6 +19,38 @@ logger = logging.getLogger() logger.info("Logging now setup") + +@app.exception_handler(Exception) +async def custom_general_exception_handler(_: Request, exc: Exception) -> JSONResponse: + """ + Custom exception handler for FastAPI to handle uncaught exceptions. It logs the error and returns an appropriate + response. + + :param _: Unused + :param exc: The exception object that triggered this handler. + :return: A JSON response indicating that something went wrong. + """ + logger.exception(exc) + return JSONResponse(content={"detail": "Something went wrong"}, status_code=status.HTTP_500_INTERNAL_SERVER_ERROR) + + +@app.exception_handler(RequestValidationError) +async def custom_validation_exception_handler(request: Request, exc: RequestValidationError) -> JSONResponse: + """ + Custom exception handler for FastAPI to handle `RequestValidationError`. + + This method is used to handle validation errors that occur when processing incoming requests in FastAPI. When a + `RequestValidationError` is raised during request parsing or validation, this handler will be triggered to log the + error and call `request_validation_exception_handler` to return an appropriate response. + + :param request: The incoming HTTP request that caused the validation error. + :param exc: The exception object representing the validation error. + :return: A JSON response with validation error details. + """ + logger.exception(exc) + return await request_validation_exception_handler(request, exc) + + # Fixes CORS issues but should be updated before deploying to prod ALLOWED_ORIGINS = ["*"] diff --git a/ldap_jwt_auth/routers/login.py b/ldap_jwt_auth/routers/login.py index 5f00ac5..94bffd3 100644 --- a/ldap_jwt_auth/routers/login.py +++ b/ldap_jwt_auth/routers/login.py @@ -52,6 +52,3 @@ def login( except LDAPServerError as exc: message = "Something went wrong" raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=message) from exc - except Exception as exc: - logger.exception(exc) - raise exc