collapse_excgroups
context manager removing exception context
#2746
Replies: 1 comment
-
You can see this with the example below: If you fiddle collapse_excgroups to I've had a dig and I'm not sure what a good solution here is. Like if you have something like Exception groups seem to handle this quite gracefully though, like if I try import traceback
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
from starlette.requests import Request
from starlette.responses import Response
from starlette.routing import Route
from starlette.testclient import TestClient
def exc_with_context(request: Request) -> None:
try:
raise Exception("ExcOuter")
except Exception as e:
# E.g. maybe someone does `log("uh oh!" + e)` and that results in a new
# exception due to bad logging. That is, explicit exception chaining
# is NOT a practical option here.
# ALso worth checking explicit chaining like `raise Exception("Blah") from e
raise Exception("ExcInner")
class CustomMiddleware(BaseHTTPMiddleware):
async def dispatch(
self,
request: Request,
call_next: RequestResponseEndpoint,
) -> Response:
try:
response = await call_next(request)
except Exception:
# print("----start inside middleware----")
# traceback.print_exc()
# print("----end inside middleware----")
raise
# exc_fmt = "".join(traceback.format_exception(ctx.value)) # type: ignore[call-arg,arg-type]
# print(exc_fmt)
return response
app = Starlette(
routes=[Route("/exc-with-context", endpoint=exc_with_context)],
middleware=[Middleware(CustomMiddleware)],
)
client = TestClient(app)
client.get("/exc-with-context") |
Beta Was this translation helpful? Give feedback.
-
collapse_excgroups
used in theBaseHTTPMiddleware
has the following code:The last line of this function updates the
__context__
of the exception object,exc
. This also adds unnecessary contextAnother exception happened during the handling of exception
.I am not sure if this is by design but this is unnecessary and can obscure details of how the exception was raised.
Fix
Both the cases, exception group object and the exception object should be handled separately. Only
raise
should be used to re-raise caught exception. For the exception group, the right way needs to be figured out.Beta Was this translation helpful? Give feedback.
All reactions