Flask
Error Handling
Register custom error handlers for HTTP exceptions.
By EZ4Code Team
errorshandlers
Code
from flask import Flask, jsonify, render_template, request
app = Flask(__name__)
@app.errorhandler(404)
def not_found(error):
if request.path.startswith("/api/"):
return jsonify({"error": "not found", "code": 404}), 404
return render_template("404.html"), 404
@app.errorhandler(500)
def server_error(error):
app.logger.exception("Internal error")
return render_template("500.html"), 500
@app.errorhandler(ZeroDivisionError)
def handle_zero(error):
return "cannot divide by zero", 400
@app.route("/boom")
def boom():
return 1 / 0Explanation
errorhandler() registers a function for a specific HTTP status code or exception class. Handlers return a response just like views and can branch on the request path to serve JSON or HTML. Logging inside 500 handlers preserves the traceback before it is converted to a response.
More Flask Snippets
Routing
Define routes with methods and dynamic parameters.
Request and Response
Access request data and build custom responses.
Jinja2 Templates
Render templates with context and template inheritance.
Blueprints
Organize an app into modular blueprints.
Session
Store per-user data in signed session cookies.
Flask-SQLAlchemy
Define models and query them with Flask-SQLAlchemy.