Flask actively throws exceptions and provides a unified sample code for exception handling.

Source: Internet
Author: User

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!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.