简体   繁体   中英

How to handle exception raised in except clause

Consider you have this kind of code for flask api:

@app.route('/doing/foo')
def foo():
 try:
      ...
 except Exception as ex:
     doing some stuff

Now doing some stuff accidentally threw another exception. How do you prevent the server from showing another generic internal server error without any clue what happened?
In other words, how do I catch exceptions that may have originated from the except clause ?

Aha! That is a 100 years question.

First option is to move to Python 3.

Python 3 has exception chaining and will print both of the exceptions - the one being handled and the one that was thrown due to the mishandling.

Second option is to implement exception chaining by yourself:

Manually inject the new exception into the one being handled using another try-except clause inside the current except: .

Keep in mind it WILL cause circular reference. Since it's a one-time exception, I wouldn't bother dealing with it. Further usage of this method will require cleaning the traceback using traceback.clear_frames() .

In a request handler, log the error and return an HTTP 500 error and some HTML noting that an "Internal error has occurred" and containing a link back to some safe point for users to restart whatever they were doing.

You can attempt to catch more specific exceptions (from most specific and common towards Exception (which is the most general of the general exceptions). You can also attempt to introspect on the exception/traceback object ( ex in your example).

Mostly you just want to ensure that you don't display internal application state to the user through their browser (possible security implications) and that you don't simply drop the user's request on the floor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM