FastAPI custom exceptions handler not working

40 Views Asked by At

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..

0

There are 0 best solutions below