When handling exceptions in FastAPI, is there a way to stop the application after raising an HTTPException?
An example of what I am trying to achieve:
@api.route("/")
def index():
try:
do_something()
except Exception as e:
raise HTTPException(status_code=500, detail="Doing something failed!")
sys.exit(1)
if __name__ == "__main__":
uvicorn.run(api)
Raising the HTTPException alone won't stop my program, and every line of code after the raise won't be executed.
Is there a good way to do something like this, or something similar with the same result?
As you already know how to solve part of raising an exception and executing the code, last part is to stop the loop. You cannot do it with
sys.exit(), you need to callstopdirectly:Or kill the gunicorn process with subprocess.run and kill/pkill if for some reason loop cannot be stopped gracefully.
Be careful of the concurrency here!