Skip to content

add_middleware causes exceptions to not be raised/handled silently #5173

@fraser-langton

Description

@fraser-langton

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google "How to X in FastAPI" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

import uvicorn
from fastapi import FastAPI
from starlette.middleware.base import BaseHTTPMiddleware


app = FastAPI()


@app.get("/info")
def info():
    # raises Exception as expected, the traceback is seen in console
    raise Exception


private_api = FastAPI()


@private_api.get("/info")
def info():
    # exception is handled silently, no traceback is seen in console
    raise Exception


app.mount("/private", private_api)


class Middleware(BaseHTTPMiddleware):

    async def dispatch(self, request, call_next):
        return await call_next(request)


app.add_middleware(Middleware)  # when this is removed, the exceptions are raised for all routes


if __name__ == '__main__':
    uvicorn.run(app, port=8000)

Description

When exceptions are raised on a subapp, the exceptions are not propagated all the way to see in console
In the example code
/info raises an exception and the full stacktrace is seen in console
/private/info does not raise the exception and only INFO: 127.0.0.1:56308 - "GET /info HTTP/1.1" 500 Internal Server Error is shown in console

Operating System

Windows

Operating System Details

No response

FastAPI Version

0.74.0

Python Version

3.8.10

Additional Context

uvicorn==0.17.6

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