Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

python - Catch an exception and displaying a custom error page

I have a Flask app. I made a custom exception in one of my libraries related to a very specific error that I would like to notify the user about.

What I would like to happen is whenever this exception is thrown have Flask go to a default page for this exception with a short explanation of what the user needs to do.

I have

class SpecificException(Exceptions):
    pass

and then

def __verify_compatible_version(self):
    if self.version != VERSION:
        raise SpecificException ("detected incompatible version")

I am not certain how to do that. The docs seem to make clear it is possible but I don't see any good examples nor advice for how to do it. How can I display a custom page to handle my custom exception?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to register an error handler for the exception. The error handler behaves like a normal view, it should return a response (or response-like data). In this case, I'm assuming you want to ultimately send a 500 status code, so that's why there's a , 500 along with the return. The handler receives the exception instance as the first argument, so you can use that when rendering a template if it has special information.

class SpecificException(Exception):
    pass

@app.errorhandler(SpecificException)
def handle_specific_exception(e):
    return render_template('errors/specific_exception.html', e=e), 500

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...