Error Handlers & Application Logging

🐍 FlaskLesson 13Advanced

Flask lets you register custom error handlers mapping to specific HTTP status codes or custom Python exceptions, while logging handles persistent audit logs.

1 Registering Error Handlers
Python — errors.py
from flask import render_template, jsonify

@app.errorhandler(404)
def page_not_found(error):
    # Return HTML template or JSON depending on request content-type
    return render_template("404.html"), 404

@app.errorhandler(Exception)
def handle_unexpected_error(error):
    app.logger.error(f"Server Error: {error}")
    return jsonify({"error": "Internal Server Error"}), 500
2 Code Challenge
Challenge: Configure Python logging to store application info and warning messages inside a persistent log file named app.log on local workspaces.