Skip to content

Throw HttpExceptions so they can be caught by middleware? #1840

@gjdanis

Description

@gjdanis

Example

import uvicorn
from fastapi import FastAPI
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
from starlette.requests import Request
from starlette.responses import Response, JSONResponse
from fastapi.exceptions import HTTPException


class RequestHandlingMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
        try:
            return await call_next(request)
        except Exception as ex:
            # logging/metrics
            return JSONResponse({"detail": repr(ex), "other_stuff": "blah"})


app = FastAPI()
app.add_middleware(RequestHandlingMiddleware)


@app.get("/exception")
def throw_exception(http_exception: bool = True, message: str = "Test message"):
    if http_exception:
        raise HTTPException(status_code=500, detail=message)
    raise Exception(message)


if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=5000, debug=True)

Description

  • Open the browser and call the endpoint /exception.
  • When called with /exception?http_exception=False we don't go into the catch block.

From here it looks HTTPExceptions are special and require using a dedicated exception handler to override how they are handled.

Can this be clarified in the documentation? Are there any plans to add the throw these exceptions so that something like a middleware could catch and log all exceptions raised while processing the request? IMO this would be easier than having to decorate route handlers with exception decorators.

Environment

  • OS: [e.g. Linux / Windows / macOS]: Windows
  • FastAPI Version [e.g. 0.3.0]: 0.54.1
  • Python version: Python 3.8.2

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions