Skip to content

Commit

Permalink
Implement custom exception handlers #6
Browse files Browse the repository at this point in the history
  • Loading branch information
VKTB committed Jan 18, 2024
1 parent 6684e68 commit 9f34150
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 4 deletions.
37 changes: 36 additions & 1 deletion ldap_jwt_auth/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 = ["*"]

Expand Down
3 changes: 0 additions & 3 deletions ldap_jwt_auth/routers/login.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 9f34150

Please sign in to comment.