5

I want to capture all unhandled exceptions in a FastAPI app run using uvicorn, log them, save the request information, and let the application continue. I seem to have all of that working except the last bit

@app.exception_handler(Exception)
async def general_exception_handler(request: APIRequest, exception) -> JSONResponse:
    ...

It runs to completion, and then the app shows

2021-05-20 11:45:45,261.261Z | ERROR | uvicorn.error | Exception in ASGI application
Traceback (most recent call last):
File "/Users/rhaven/code/projectblue-api/venv/lib/python3.8/site-packages/uvicorn/protocols/http/httptools_impl.py", line 385, in 
...
 File "/Users/rhaven/code/projectblue-api/venv/lib/python3.8/site-packages/fastapi/routing.py", line 149, in run_endpoint_function
return await dependant.call(**values)
File "./app/main.py", line 236, in internal_testing
raise Exception("test exception from blue-api")

How do I eat the exception once I've handled it?

Cheers

Richard Haven
  • 63
  • 1
  • 4
  • I found someone else who succeeded with the [exception handler](https://stackoverflow.com/a/65760929/15193055) as I did; no mention if his server dies as mine does I found ycd's answer on – Richard Haven May 20 '21 at 22:13
  • I also find [a custom router solution](https://github.com/tiangolo/fastapi/issues/2750#issuecomment-775526951) from ycd. As the handler is working perfectly apart from not eating the exception (exception notifier rather than handler?), I hope I can just stop the ISE without going this route – Richard Haven May 20 '21 at 22:15
  • This will help: https://stackoverflow.com/a/75822748/257299 – kevinarpe Mar 23 '23 at 12:03

0 Answers0