Get the App
SLTechnology News&Howtos  ›  Development  › 

Example Analysis of Request interrupt and ErrorHandler

Shulou Source: shulou.com Published: 2022-06-03 19:17:32 09月18日 Update

This article mainly introduces the Request interrupt and ErrorHandler example analysis, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

Overview

In the view function, if you need to interrupt request, you can use abort (500) or direct raise exception. Of course, we also need to return an error message to the front end, so we need to customize the ErrorHandler. Generally speaking, only two handler are needed, one is a 404 error, and the other is a server-side error such as 500. Of course, you can also customize errors.

Code list

The following is a sample code, main is a blueprint or app, if a 404 or 500error occurs, a Json object is returned to the request segment.

From flask import jsonifyfrom. Import main@main.errorhandler (404) def error_404 (error): "" this handler can catch all abort (404) and cannot find corresponding router processing requests "response = dict (status=0, message=" 404 Not Found ") return jsonify (response), 404@main.errorhandler (Exception) def error_500 (error):" this handler can catch all abort (500) and raise exeception. "" Response = dict (status=0, message= "500Error") return jsonify (response), 400class MyError (Exception): "" Custom error class "" pass@main.errorhandler (MyError) def MyErrorHandle (error): response = dict (status=0, message= "400Error") return jsonify (response), error handling for 400blueprints

Writing error handlers in the blueprint is a little different. If you use the errorhandler modifier, only the errors in the blueprint will be triggered. If you want to register a global error handler, use app_errorhandler.

For example:

From. Import auth@auth.app_errorhandler (404) def error_404 (error): response = dict (status=0, message= "404 Not Found") return jsonify (response), 404 Thank you for reading this article carefully. I hope the article "Request interruption and sample Analysis of ErrorHandler" shared by the editor will be helpful to you. At the same time, I also hope you will support us, pay attention to the industry information channel, and more related knowledge is waiting for you to learn!

Tags: Error article blueprint processing example analysis code domicile program different two value information global interest function front end only at the same time object Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft Shulou Technology Huawei OPPO Reno macOS