APIs with Express · Chapter 9 of 29
Error handling
By the end of this chapter you can send every error out through one handler, as JSON, with the right status, and without telling strangers how your server works inside. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: Middleware
- 5 tasks
- Express
- In the all labs plan
The first 2 chapters of APIs with Express are free. This one comes with the all labs plan.
Why you need this
At 4:10 pm the database restarts, and for forty seconds partner cafés get an HTML page starting Error: connection reset by 10.0.0.12, with file paths from Tapri's server. Blue Tokai's developer sends Meera a screenshot: their app could not read it, and now they know an address on Tapri's internal network.
With what you know, every route would wrap its code in try/catch and build its own error answer, each a little different. Any error a route misses goes to Express's built-in handler, which answers an HTML page with the stack trace in it.
What you build: 5 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
HttpError: an error that knows its status
Finish the exported class HttpError, which extends Error. new HttpError(409, 'Order already paid') has status 409, message 'Order already paid' and name 'HttpError', is an instance of both Error and HttpError, and has a stack that contains its message.
Add a static method HttpError.notFound(what), which returns a new HttpError with status 404 and the message '<what> not found': HttpError.notFound('Order 7') has the message 'Order 7 not found'.
- Task 2 · interview question
Interview: errorHandler, the handler Express never calls
Fix errorHandler(). The middleware it returns must be used by Express for errors: thrown in a route (a status 418 error answers 418 with { error: 'Tapri only makes chai' }), rejected in an async route (an error with no status answers 500 with its message in error), or passed with next(err) (409 with { error: 'Order already paid' }).
Today Express skips it, and its own HTML page answers instead. A request without an error never reaches it: an unknown path is still a 404.
- Task 3
Async order routes that simply throw
In createApp, write the two async order routes. They throw (or let a rejection through) instead of answering errors themselves, and Express 5 passes the errors to errorHandler.
POST /orders with JSON { item, qty } saves { item, qty, total } with await db.saveOrder and answers 201 with the saved order: { id: 1, item: 'masala-chai', qty: 2, total: 80 }. An item that is not on the menu throws a 422 HttpError: { error: 'Pick an item from the menu' }.
GET /orders/:id answers 200 with the order from await db.findOrder (the id as a number), or throws HttpError.notFound, so GET /orders/9 answers 404 with { error: 'Order 9 not found' }.
When the database rejects, the answer is a 500 in JSON within 1.5 seconds, not a hung request. Tasks 1 and 2 must be done first.
- Task 4
notFound: JSON for unknown routes and broken bodies
Finish notFound, the middleware createApp already registers after the routes. A request that reaches it matched no route: it passes on a 404 HttpError with the message 'No route for <method> <path>', so GET /nope answers 404 with { error: 'No route for GET /nope' } and DELETE /orders/1 answers { error: 'No route for DELETE /orders/1' }.
Broken JSON (400) and a body over 1kb (413) must answer JSON too, with a string in error: the fixed errorHandler from task 2 takes care of them.
- Task 5
errorHandler: hide server details in production
Finish errorHandler({ production }). The status is err.status when it is a whole number from 400 to 599, and 500 otherwise (a status of 302, or the text 'teapot', answers 500).
A 4xx answers { error: err.message }, in production too: GET /orders/5 there answers 404 with { error: 'Order 5 not found' }.
A 5xx answers { error: err.message, stack: err.stack } while developing (production false, the default), and only { error: 'Something went wrong' } in production, with nothing else in the body: a 503 'Kitchen gas leak in block B' answers 503 with { error: 'Something went wrong' }, and a database error that names 10.0.0.12 must not leak that address.
What you will learn
- Error-handling middleware: one function, after the routes, that every error goes to.
- Async errors in Express 5: a rejected await reaches that function with no try/catch.
- Error classes: errors that carry their own status.
- A JSON 404, and what production may see: the request no route matched, and the details a 5xx must hide.
More in Middleware
Build "Error handling" yourself
Partner cafés want Tapri’s menu online by Friday: you build its API. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
The first 2 chapters of APIs with Express are free. This one comes with the all labs plan.