Updated: October 26, 2026
A phone app calls an API and gets an error. The app wants to show a short, kind message. But the error comes back in a shape the app did not expect, so it shows "undefined" instead.
This happens a lot. FastAPI is easy to work with. Its default errors just do not all look alike.
Below, every error gets one JSON shape, and a few tests check it.
Tested with: Python 3.13.5, FastAPI 0.161.0, Pydantic 2.14.1 and pytest 9.1.1 on Linux. Outputs are pasted from a single run.
Two words first
Exception: a Python error that stops the normal flow of code.
Exception handler: a function that catches one kind of exception and turns it into a response.
FastAPI lets you register a handler for each kind of exception. That is the whole trick.
The problem: two shapes by default
Here is a tiny app with no custom handlers.…