Performance: Error handler decorators
This affects how quickly errors are caught and handled during request processing, impacting response time and user experience.
from flask import Flask, jsonify app = Flask(__name__) @app.errorhandler(ZeroDivisionError) def handle_zero_division(e): return jsonify(error='Division by zero error'), 400 @app.route('/') def index(): 1 / 0 # triggers error handler
from flask import Flask app = Flask(__name__) @app.route('/') def index(): 1 / 0 # causes ZeroDivisionError # No error handler defined
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No error handler | N/A | N/A | Blocks response rendering due to server error | [X] Bad |
| Error handler decorator | N/A | N/A | Fast error response avoids blocking UI updates | [OK] Good |
@app.errorhandler decorator in Flask?@app.errorhandler is used to register functions that handle specific errors gracefully.@app.errorhandler decorator takes an integer error code like 404, not a string or undefined constant.@app.errorhandler(500)
def internal_error(error):
return 'Server Error Occurred', 500
@app.route('/')
def index():
raise Exception('Oops')index route raises a generic Exception, which triggers a 500 Internal Server Error.@app.errorhandler(500) catches this error and returns the custom message with status 500.@app.errorhandler(403)
def forbidden():
return 'Forbidden Access', 403forbidden has no parameters, so Flask will raise a TypeError.@app.errorhandler decorators stacked on the same function handles both errors with one function.Pass the test and this pattern moves unknown