Flask actively throws exceptions and provides a unified sample code for exception handling.
This article mainly introduces flask's active exception throws and unified exception handling. The details are as follows.
When an exception occurs in the background during development, but you do not want to display the exception to the user or want to handle the exception in a unified manner, you can use abort to throw an exception and capture the page after the exception is returned.
Actively throw an exception:
@user.route('/testError') def testError(): print ('testError') abort(404)
Use the decorator errorhandler to capture exceptions:
@user.errorhandler(404) def error(e): return render_template('exception/404.html')
In this way, you can customize the exception page. If error_handler is used, only errors in this blueprint will be triggered. To handle global exceptions, app_errorhandler must be used.
Write all Exception Handling in a blueprint.
#coding:utf-8 #error from flask import Blueprint, render_template, redirect,session,request,abort exception = Blueprint('exception',__name__) @exception.app_errorhandler(404) def error(e): return render_template('exception/404.html')
Register the blueprint in view. py
app.register_blueprint(exception, url_prefix='/error')
In this way, all the exceptions triggered by the blueprint can be handled.
Summary
The above is all about the sample code for actively throwing exceptions and unified Exception Handling in flask. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!