📎 Webclip
Using Express.js Routes for Promise-based Error Handling
The article starts from a typical Express app where each route repeats .then() and .catch() logic, which becomes hard to maintain as the number of routes grows. It then compares utility functions and error middleware with a custom promise middleware that attaches res.promise() and centralizes response handling.
Reading notes#
- Express does not support promise-based route handlers by default, so many tutorials lead developers into repeating response and error logic in each route.
- A small example app uses a
usersRouter, auserService, and promise-returning service methods to show the repeated pattern in route handlers. - The first alternative is to extract response and error handlers into utility functions, which removes some duplication but still requires imports and per-route wiring.
- The second alternative is to send errors to Express error middleware with
next, but route handlers still need separate success handling and explicit.catch(next)calls. - The proposed approach adds
res.promise()through middleware, letting routes pass either a promise, a function, or a value and centralizing success and error handling. - The app keeps error middleware for synchronous failures, and those errors are forwarded into the same centralized handling path with
Promise.reject(). res.promise()is presented as optional, since direct response handling is still useful for redirects and stream piping.- The redirect example uses
async/awaitto fetch a URL and still sends errors throughres.promise(). - The stream example pipes an image response directly and notes that stream errors need separate handling depending on when they occur.
- The article says the pattern can also be extended to customize status codes, content type, and error formatting, while keeping route logic in one place.
