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
javascript
import { parsePhoneNumberFromString } from 'libphonenumber-js'; export class PhoneValidationError extends Error { constructor(message, code) {
Normalizing phone numbers with typed errors
validation
error-handling
custom-errors
Intermediate
6 steps
typescript
import { Injectable, computed, inject, signal } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { firstValueFrom } from 'rxjs';
Optimistic updates with Angular signals
signals
optimistic-updates
state-management
Intermediate
9 steps
python
import os from datetime import datetime, timezone import jwt
JWT bearer auth as a FastAPI dependency
authentication
jwt
dependency-injection
Intermediate
7 steps
rust
use std::error::Error; use std::path::Path; use serde::Deserialize;
Custom CSV deserialization with serde in Rust
serde
csv
deserialization
Intermediate
7 steps
go
package config import ( "fmt"
Loading typed config from environment variables in Go
configuration
environment-variables
type-parsing
Beginner
8 steps
rust
use std::time::Duration; use axum::{extract::State, http::StatusCode, response::IntoResponse, Json}; use serde::Serialize;
A timeout-guarded health check in Axum
health-check
timeout
error-handling
Intermediate
6 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.