Do not pollute exception context in Middleware#2976
Conversation
Avoid passing `anyio.EndOfStream` as exception context when reraising the exception in middleware. Instead try to preserve the original context.
635b6a6 to
ec88bf0
Compare
|
I think we'd want to merge #2830 instead. Can you try that PR? |
| # propagated as a cause with the reraise. This is necessary in order | ||
| # to prevent `anyio.EndOfStream` from polluting the exception | ||
| # context. | ||
| raise app_exc from app_exc.__cause__ or app_exc.__context__ |
There was a problem hiding this comment.
I guess what happens if the exception has no cause or context? Then does anyio.EndOfStream become the new cause / context?
There was a problem hiding this comment.
If neither the context nor cause are present then this is equivalent to raise app_exc from None which suppresses the exception context and just shows the raised exception. This means that anyio.EndOfStream does not show up in the traceback.
Should I expand the comment to make this more clear?
This is a desired solution for me since when the anyio.EndOfStream was propagated in traceback as the innermost exception (context of app_exc) - it caused our Error Reporting (tool from Google cloud that aggregates encountered errors from logs) to group all our API errors into single group as the innermost exception was always the same.
I can not test it directly at the moment but I believe that the mentioned PR does not change the exception behavior for the part that was changed in this PR. Furthermore the passing of the context there was is still just a suggestion in one comment. |
I managed to test the #2830 PR even with the last suggestion there to add context/cause to the exception and I can confirm that it does not cover the issue solved in this PR |
Kludex
left a comment
There was a problem hiding this comment.
Makes sense. Great PR.
Sorry the delay!
Summary
Avoid passing
anyio.EndOfStreamas exception context when reraising the exception inBaseHTTPMiddleware. Instead try to preserve the original context.Checklist