Performance: API error handling
This affects the responsiveness and stability of API endpoints, impacting how quickly errors are detected and communicated to clients.
from flask import Flask, jsonify app = Flask(__name__) @app.errorhandler(ZeroDivisionError) def handle_zero_division(error): return jsonify({'error': 'Division by zero error'}), 400 @app.route('/data') def get_data(): data = 1 / 0 # This will raise ZeroDivisionError return jsonify({'data': data})
from flask import Flask, jsonify app = Flask(__name__) @app.route('/data') def get_data(): try: # Simulate data fetching data = 1 / 0 # This will raise ZeroDivisionError return jsonify({'data': data}) except Exception as e: return jsonify({'error': str(e)}), 500
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Broad try-except in route | 0 (API only) | 0 | 0 | [X] Bad |
| Specific Flask errorhandler | 0 (API only) | 0 | 0 | [OK] Good |
@app.errorhandler in a Flask API?@app.errorhandler@app.errorhandler catches errors [OK]@app.errorhandler decorator takes an integer status code like 404 without quotes.from flask import abort, jsonify
@app.errorhandler(400)
def bad_request(error):
return jsonify({'error': 'Bad Request'}), 400
@app.route('/test')
def test():
abort(400)/test?abort(400) call triggers the 400 error handler defined by @app.errorhandler(400).@app.errorhandler(500)
def internal_error():
return {'error': 'Server Error'}, 500internal_error has no parameters, so Flask will raise a TypeError.KeyError raised in your routes. Which of the following is the best way to implement this?KeyError, use it directly in @app.errorhandler(KeyError).Pass the test and this pattern moves unknown