I am new to flask and python so please pardon me if the answer is obvious. My flask app has a scheduler and which opens many threads at different time that do specific different work and also run some commands on the terminal and get their result.
Now I am a little hesitant in what if something goes wrong and the scheduler is unable to spawn a thread or any other issue come while running the application on production.I have my try catch in place but what if some day I miss a very obvious try catch.I don't want my application to stop on production instead it should log the exception and keep accepting request or scheduling the other task with out stopping the application main thread.
So I wanted to implement a global exception handler that is able to catch any and all types of exception not just the API exception.
python 3.8 flask 3.0
I have tried adding the below code but the application stops after logging and in case of exception on my thread it is unable to catch the exception.
def global_exception_handler(exc_type, exc_value, exc_traceback):
try:
# Log or handle the exception here
print(f"##########Global exception handler caught: {exc_value}")
except Exception as e:
print(f"##########Global exception unable to handle exception")
sys.excepthook = global_exception_handler
and this also
@app.errorhandler(Exception)
def handle_exception(error):
response = jsonify({'message': str(error)})
response.status_code = 500
return response