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 HTTPException to JSON for APIs
  • Log unhandled exceptions
  • Never run debug mode in production

More most-asked Flask questions

← All Flask questions