Skip to content

Commit

Permalink
Gracefully hanlde exceptions that happen after successful request.
Browse files Browse the repository at this point in the history
With the current implementation, any exception in the ASGI app will
make mangum return a response with 500, even though the application may
have already correctly generated a valid response. In those cases we
want to return the valid response and log the error, rather than fail.

One example where this would manifest: failures in BackgroundTasks in
FastAPI.

This makes it inline with running FastAPI (and other ASGI) applications
standalone where failures in the background tasks will return not make
the whole request fail.
  • Loading branch information
tasn committed Dec 31, 2021
1 parent 6da7e51 commit cecd475
Showing 1 changed file with 7 additions and 0 deletions.
7 changes: 7 additions & 0 deletions mangum/protocols/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,13 @@ async def run(self, app: ASGIApp) -> None:
try:
await app(self.request.scope, self.receive, self.send)
except BaseException as exc:
if self.state is HTTPCycleState.COMPLETE:
# We want to log, but skip exceptions from background tasks
self.logger.exception(
"An exception has occurred after successful completion of request"
)
return

self.logger.error("Exception in 'http' protocol.", exc_info=exc)
if self.state is HTTPCycleState.REQUEST:
await self.send(
Expand Down

0 comments on commit cecd475

Please sign in to comment.