Performance: Why error handling matters
Error handling affects user experience by preventing unexpected page crashes and reducing unnecessary server load during failures.
from flask import Flask, jsonify app = Flask(__name__) @app.route('/') def index(): try: result = 10 / 0 return str(result) except ZeroDivisionError: return jsonify({'error': 'Division by zero is not allowed'}), 400
from flask import Flask app = Flask(__name__) @app.route('/') def index(): # No error handling result = 10 / 0 # This will crash the app return str(result)
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No error handling | N/A | N/A | Blocks rendering with error page | [X] Bad |
| Proper error handling with JSON response | Minimal | 0 | Fast paint with error message | [OK] Good |
@app.errorhandler(code) decorator to catch errors by status code.@app.errorhandler(404)
def page_not_found(error):
return 'Oops! Page missing.', 404
@app.route('/')
def home():
return 'Welcome!'@app.errorhandler(500)
def internal_error():
return 'Server error occurred', 500Pass the test and this pattern moves unknown