Flask · Lesson 8 of 15
Error Handlers and Logging
Catch 404/500 consistently and log with a request id.
- Intermediate
- 14 min read
- 3 objectives
Before this lessonLesson 7: JSON APIs
What you will learn
- Register error handlers
- Log exceptions
- Add a request id
Your Progress
0 of 15 lessons 0%
- Lessons0 / 15
- Completed0
- Est. time left~ 4 hours
Create a free account to keep your progress on every device.
Users should see a clean error page. You should see a stack trace with a request id in the logs.
Handlers
import logging
from flask import render_template, jsonify, g
log = logging.getLogger(__name__)
@app.errorhandler(404)
def not_found(e):
if request.path.startswith("/api/"):
return jsonify(error="Not found"), 404
return render_template("404.html"), 404
@app.errorhandler(500)
def server_error(e):
log.exception("unhandled error request_id=%s", g.get("request_id"))
if request.path.startswith("/api/"):
return jsonify(error="Internal Server Error"), 500
return render_template("500.html"), 500Request id middleware
import uuid
@app.before_request
def stamp_id():
g.request_id = request.headers.get("X-Request-Id", uuid.uuid4().hex)
@app.after_request
def set_id(response):
response.headers["X-Request-Id"] = g.request_id
return responseConfigure logging once in the factory: structured JSON in production, pretty traces in development.
File Uploads and Static MediaAccept files safely, store them outside the code tree and serve them in development.