Flask interview question · Most asked
How do you handle errors in Flask, including JSON APIs?
Summary
Register handlers with @app.errorhandler(code_or_exception) (or bp.app_errorhandler) and raise abort(code) or custom exceptions. For APIs, return JSON for HTTPExceptions by handling them generically.
Longer Answer
Werkzeug's HTTPException carries code, name and description. A generic handler can convert any of them to JSON. Unhandled exceptions become 500s; log them and return a safe message. In debug mode, Flask shows the interactive debugger, which must never be enabled in production because it allows code execution.
Code Example
from werkzeug.exceptions import HTTPException
@app.errorhandler(HTTPException)
def handle_http(e: HTTPException):
return {"error": e.name, "message": e.description}, e.code
class InsufficientStock(Exception):
pass
@app.errorhandler(InsufficientStock)
def handle_stock(e):
return {"error": "insufficient_stock", "message": str(e)}, 409
Key Points
@app.errorhandler(404)/ custom exceptions- Convert
HTTPExceptionto JSON for APIs - Log unhandled exceptions
- Never run debug mode in production
More most-asked Flask questions
- How do you access request data and build responses in Flask?
- How do Flask sessions work and what are their security implications?
- What is the application factory pattern in Flask and why use it?
- What is Flask and what does 'microframework' mean?
- Explain Flask's application context and request context.
- What are Blueprints in Flask?
- How does routing work in Flask, including variable rules and HTTP methods?
- How do you use SQLAlchemy with Flask (Flask-SQLAlchemy 3.x)?