python 43 lines · 5 steps

Centralized JSON error handling in Flask

A Flask blueprint that turns exceptions and 404s into consistent JSON error responses.

Explained by highlit
1import logging
2import traceback
3 
4from flask import Blueprint, jsonify, request
5from werkzeug.exceptions import HTTPException
6 
7log = logging.getLogger(__name__)
8errors = Blueprint("errors", __name__)
9 
10 
11@errors.app_errorhandler(404)
12def handle_not_found(error):
13 response = jsonify(
14 {
15 "error": "not_found",
16 "message": error.description or "The requested resource was not found.",
17 "path": request.path,
18 }
19 )
20 return response, 404
21 
22 
23@errors.app_errorhandler(HTTPException)
24def handle_http_exception(error):
25 return (
26 jsonify({"error": error.name.lower().replace(" ", "_"), "message": error.description}),
27 error.code,
28 )
29 
30 
31@errors.app_errorhandler(500)
32@errors.app_errorhandler(Exception)
33def handle_internal_error(error):
34 log.error("Unhandled exception on %s %s\n%s", request.method, request.path, traceback.format_exc())
35 return (
36 jsonify(
37 {
38 "error": "internal_server_error",
39 "message": "An unexpected error occurred. Please try again later.",
40 }
41 ),
42 500,
43 )
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1App-wide error handlers keep every failure response in one predictable JSON shape.
  2. 2Handler specificity matters: Flask picks the most specific matching handler, so order broad catch-alls last.
  3. 3Log the traceback server-side but return a generic message to clients to avoid leaking internals.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Centralized JSON error handling in Flask — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code