I have a simple FastAPI setup with a custom middleware class inherited from BaseHTTPMiddleware
. Inside this middleware class, I need to terminate the execution flow under certain conditions. So, I created a custom exception class named CustomError
and raised
the exception.
from fastapi import FastAPI, Request
from starlette.middleware.base import (
BaseHTTPMiddleware,
RequestResponseEndpoint
)
from starlette.responses import JSONResponse, Response
app = FastAPI()
class CustomError(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return self.message
class CustomMiddleware(BaseHTTPMiddleware):
def execute_custom_logic(self, request: Request):
raise CustomError("This is from `CustomMiddleware`")
async def dispatch(
self,
request: Request,
call_next: RequestResponseEndpoint,
) -> Response:
self.execute_custom_logic(request=request)
response = await call_next(request)
return response
app.add_middleware(CustomMiddleware)
@app.exception_handler(CustomError)
async def custom_exception_handler(request: Request, exc: CustomError):
return JSONResponse(
status_code=418,
content={"message": exc.message},
)
@app.get(path="/")
def root_api():
return {"message": "Hello World"}
Unfortunately, FastAPI couldn't handle the CustomError
even though I added custom_exception_handler(...)
handler.
Questions
- What is the FastAPI way to handle such situations?
- Why is my code not working?
Versions
- FastAPI - 0.95.2
- Python - 3.8.13