Error handling across the stack
One error shape from database to toast: stable codes and field maps on the server, one typed failure on the client, and a screen state per failure kind.
End-to-end type safetyValidating on the client and the server
Error handling across the stack
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- Every layer fails differently, such as a constraint violation, a thrown exception, or a dropped connection, and the job is to map each one to a single error shape before it leaves the server.
- An error body has a stable machine code for the client to branch on, a human message for display, and an optional map of field errors for forms.
- A catch-all handler on the server turns unexpected exceptions into a generic 500 and logs the details, so stack traces and SQL never reach the browser.
- Unknown routes and malformed JSON need to return the same error shape as everything else, otherwise the client's parser meets plain text.
- The client needs a distinct state for each failure kind, namely validation, unauthenticated, not found, and network or server failure, because each calls for a different thing on screen.
Where errors come from
A single click on “Add task” can fail in at least six ways:
- The input fails validation.
- The session expired.
- The project belongs to someone else.
- The database rejects the row (a unique or foreign-key constraint).
- The server’s own code throws.
- The network drops before any of that.
Each one starts in a different layer with a different representation: a Zod issue, a missing cookie, a null row, a driver exception, a TypeError, a rejected fetch promise. If each reaches the user raw, the UI becomes a pile of special cases. The core problem is that the browser needs to make a decision about each failure, and it cannot decide from a stack trace.
The answer is to translate at the boundary. The server turns every failure into one shape. The client turns every response into one typed failure. The screen switches on that.
One shape on the wire
Taskboard’s API errors look like this:
{"error":{"code":"validation","message":"Fix the highlighted fields","fields":{"title":["Give the task a title"]}}}
Three parts, three audiences:
code: stable and machine-readable. The client branches on it. It never changes wording.message: for display. Free to rewrite or translate.fields: optional map from input name to messages. Forms use it to put errors next to inputs.
If you know structured error handling and RFC 7807, this is the same idea in a simpler envelope; Problem Details is the standard to reach for when other teams consume your API. For a private client-and-server pair, a small custom shape is fine as long as it is uniform.
One place on the server
In Hono, onError is the single funnel:
.onError((err, c) => {
if (err instanceof ApiError)
return c.json({ error: { code: err.code, message: err.message, fields: err.fields } }, err.status);
if (err instanceof SyntaxError)
return c.json({ error: { code: "bad_json", message: "Request body is not valid JSON" } }, 400);
console.error(err);
return c.json({ error: { code: "internal", message: "Something went wrong on our side" } }, 500);
})
Anything the code throws on purpose is an ApiError carrying a status and a code. Anything else is a bug, and a bug gets a generic message while the real error goes to the log. A stack trace in a response body is a gift to attackers and confusing to users. The same funnel exists in Express as an error-handling middleware; see Express error handling and async routes.
I ran this and the responses were, in order: bad credentials 401 {"error":{"code":"bad_credentials",...}}, a duplicate signup 409 {"error":{"code":"email_taken",...,"fields":{"email":["Already registered"]}}}, and a request without a session cookie 401 {"error":{"code":"unauthenticated","message":"Sign in to continue"}}.
The gaps I hit
Two things I got wrong on the first run are worth passing on.
Malformed JSON came back as a 500. I posted not json to /api/projects and the SyntaxError from the body parser fell through to the generic handler. The caller sent bad input, so this should be a 400. The SyntaxError branch above is the fix, and the retest returned 400 {"code":"bad_json"}.
Unknown routes came back as plain text. GET /api/nothing returned the literal text 404 Not Found. A client that always calls res.json() on failures would throw a parse error and hide the real problem. Registering .notFound(...) to return the same JSON shape fixed it: {"error":{"code":"not_found","message":"No such route"}} [404].
The lesson: test the failures, not only the happy path. Every real error shape bug in this app was found by sending bad requests to the running server.
One typed failure on the client
On the other side, one function converts any non-OK response into a thrown value the UI can inspect:
export class ApiFailure extends Error {
constructor(public status: number, public code: string, message: string,
public fields?: Record<string, string[]>) { super(message); }
}
export async function unwrap<T>(res: Response & { json(): Promise<T> }): Promise<T> {
if (res.ok) return res.status === 204 ? (undefined as T) : res.json();
const body = (await res.json().catch(() => null)) as any;
throw new ApiFailure(res.status, body?.error?.code ?? "unknown",
body?.error?.message ?? res.statusText, body?.error?.fields);
}
The .catch(() => null) matters: it covers a proxy returning an HTML error page. A fetch that never gets a response throws its own TypeError, which you handle as “network failure”. That gives the screen exactly four failure kinds to design for.
One state per failure kind
| Kind | Signal | What the user sees |
|---|---|---|
| Validation | code: validation, fields |
Messages beside inputs, form stays filled |
| Signed out | 401 |
Send to sign-in, remember where they were |
| Not found / forbidden | 404 |
A “not found” page, not a toast |
| Unexpected | 500 or network error |
Generic message and a retry |
Notice that the right UI is different each time: a toast is the wrong answer for a validation error, and a form message is the wrong answer for a lost connection. Unexpected render-time errors in components are a separate mechanism; error boundaries catch those. And if you use TanStack Query, its error field is where a thrown ApiFailure ends up, covered in calling the API from the client.
What the video covers
Web Dev Simplified’s “How To Handle Errors Like A Senior Dev” is about 32 minutes, published February 2026. Its description says it shows how to handle errors in a type-safe way and links to his videos on discriminated unions and the satisfies keyword. It is general TypeScript error handling, not specifically HTTP, so treat it as the client-side half of this lesson. I could not read a transcript. The 1programmer video on TanStack Query errors is about five minutes and linked as a second view.
Where this fits
Errors can now travel the stack intact, as long as a request reaches the API at all. When the browser and API live on different origins, the browser can refuse before the server’s code even runs. Next: CORS and cross-origin setups.
Check yourself
Why does the error body carry a code as well as a message?
The message is for people and may change or be translated, while the code is stable, so the client can branch on it without parsing text.
What happened when I posted invalid JSON before adding a handler for it?
The JSON parser threw a SyntaxError that nothing caught, so the generic handler returned a 500 even though the caller's input was at fault.
Why must unknown routes return JSON too?
The client's fetch wrapper assumes failures have a JSON body, so a plain text 404 breaks the parse and hides the real problem.
Which failure should not show a toast with the server's message?
An unexpected 500, because its detail may leak internals, so the user sees a generic message and the details go to the server log.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.