-
-
Notifications
You must be signed in to change notification settings - Fork 953
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
middleware causes exceptions to not be raised/handled silently (back again) #2625
Comments
I have the same issue |
@daniilmastrangeli a fix I have found for now is to add_exception_handler which catches the exception and if re-raised will display the trace to stdout as expected import uvicorn
from fastapi import FastAPI, Request
from starlette.middleware.base import BaseHTTPMiddleware
app = FastAPI()
class MyExc(Exception):
...
@app.get("/info")
def info():
raise MyExc
private_api = FastAPI()
@private_api.get("/info")
def info():
raise MyExc
app.mount("/private", private_api)
class Middleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
return await call_next(request)
def re_raise_exception(_: Request, exc: Exception):
raise exc from exc
app.add_middleware(Middleware)
app.add_exception_handler(Exception, re_raise_exception) # raises the exception in the handler which results in getting handled by a different context
if __name__ == "__main__":
uvicorn.run(app, port=8000) |
@fraser-langton ty, it's worked |
The root cause is here: #2194 (comment). For more references, see also: fastapi/fastapi#8577 (comment) |
This regression happened on 0.29.0. |
I've started some work on #2696. |
Is there a way to work around this for background tasks as well? The workaround functions for me when the exception occurs in my endpoint's code. But if the endpoint starts a background task and that task throws an exception, it gets lost. |
@mike-schiller I haven't got one, didn't need it for background tasks personally |
You can use https://github.com/adriangb/asgi-background which isn't impacted by this. |
Thanks @adriangb. I'll check that out. For the moment I implemented a decorator that I apply to all my background tasks to wrap them in try/except with logging. |
Can someone test #2812, please? |
Regression of #1976 #1977 #1609 #1940
This time I have noticed that changing
MyExc(Exception)
toMyExc(BaseException)
means the error does get sent to stdout (if that helps) I tried to have a dig but I am not too sure where that catch exception is that is catching the Exception (and silently passing) and not the BaseExceptionstarlette==0.37.2
fastapi==0.111.0
Important
The text was updated successfully, but these errors were encountered: