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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1App-wide error handlers keep every failure response in one predictable JSON shape.
- 2Handler specificity matters: Flask picks the most specific matching handler, so order broad catch-alls last.
- 3Log the traceback server-side but return a generic message to clients to avoid leaking internals.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/centralized-json-error-handling-in-flask-explained-python-e342/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.