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
python
class Parser: def __init__(self, text): self.tokens = self._tokenize(text) self.pos = 0
A recursive descent arithmetic parser
recursive-descent
tokenizer
operator-precedence
Intermediate
9 steps
rust
use axum::{ extract::{FromRef, FromRequestParts}, http::{header, request::Parts, StatusCode}, RequestPartsExt,
How a JWT extractor works in Axum
jwt
authentication
extractors
Intermediate
8 steps
python
import re from dataclasses import dataclass, field
Building a table of contents from Markdown
regular-expressions
parsing
slugification
Intermediate
9 steps
python
from flask import Blueprint, render_template, redirect, url_for, session, request from wtforms import Form, StringField, SelectField, IntegerField from wtforms.validators import DataRequired, Email, NumberRange
A multi-step signup wizard in Flask
blueprints
session-state
form-validation
Intermediate
10 steps
rust
#[derive(Deserialize)] pub struct CreateArticle { title: String, body: String,
Building a create endpoint in Axum
extractors
json-deserialization
sqlx
Intermediate
7 steps
go
func UploadDocument(c *gin.Context) { fileHeader, err := c.FormFile("file") if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "file is required"})
Handling multipart uploads in Gin
multipart-upload
validation
error-handling
Intermediate
9 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.