2

I'm implementing custom exceptions in middleware and I want to raise an exception and expecting a JSON response with error message and code, when condition fails as mentioned below in middleware . But receiving INTERNAL SERVER ERROR

Using version : fastapi[all]==0.99.0

# main.py

from fastapi import FastAPI
from starlette.middleware.base import BaseHTTPMiddleware
from exceptions import CustomException
from handlers import custom_exception_handler

app = FastAPI()

# Middleware function
class ValueCheckMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request, call_next):
        # Check the value in the request
        value = request.headers.get("X-Value")
        if value != "1":
            raise CustomException()
        # Call the next middleware or route handler
        response = await call_next(request)
        return response

# Register middleware
app.add_middleware(ValueCheckMiddleware)

# Register custom exception handler
app.add_exception_handler(CustomException, custom_exception_handler)

# Route
@app.get("/")
async def read_root():
    return {"message": "Hello World"}



# handlers.py
from fastapi import HTTPException, Request, JSONResponse
from exceptions import CustomException

async def custom_exception_handler(request: Request, exc: CustomException) -> JSONResponse:
    return JSONResponse(status_code=exc.status_code, content={"detail": exc.detail})



# exceptions.py
from fastapi import HTTPException

class CustomException(HTTPException):
    def __init__(self, detail="Value is not one", status_code=400):
        super().__init__(status_code=status_code, detail=detail)

I want a json response when there is an exception in middleware. But getting INTERNAL SERVER ERROR

Expectation: I want a json response when there is an exception in middleware..

5
  • What's in your server logs? Does the traceback point to the raise CustomException() line? Commented Mar 15, 2024 at 5:30
  • In addition to the link provided in the banner above, please have a look at this answer and this answer, as well as this answer and this answer Commented Mar 15, 2024 at 6:33
  • @Chris Yeah I checked the provided answers, and I can achieve the expectations using these methods, but I'm looking for a very specific problem. The problem is I can raise custom exceptions in utility functions or all other services, but I can't raise it inside class-based middleware without using try/except block. That's the main problem. Any suggestions here ? Commented Mar 16, 2024 at 6:58
  • @Gaberocksall Yes traceback points to my CustomException() but there is some issue with while raising it and returning response Here are the logs : Link Commented Mar 16, 2024 at 7:09
  • I am also face this problem, finally, I just return return JSONResponse(status_code=status.HTTP_401_UNAUTHORIZED, content={"message": "Could not validate credentials"}, headers={"WWW-Authenticate": "Bearer"}) Commented Nov 28, 2024 at 8:02

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.