Handbooks / Node.js / Chapter 6
Error Handling and Async Patterns
7 pages · ~5 min✓ Reviewed
Builds on Express Routing and Middleware. Next up: Databases from Node.
Callbacks and the Error-First Convention
1. Definition and signature
- Callback = function passed to an async API
- The event loop calls it later, never inline in the caller's stack
- Error-first:
cb(err, result) erris null or undefined on success
2. Callbacks vs promises
| Callback | Promise | |
|---|---|---|
| Return or await | No | Yes |
| Nesting | callback hell | flat chain |
| Errors | cb(err) | .catch |
3. Example: readFile
- Check
errfirst and return util.promisifywraps this style into a promise
javascript
function read(path, cb) { fs.readFile(path, 'utf8', (err, data) => { if (err) return cb(err); cb(null, data); }); } const readP = util.promisify(read);
4. Interview Point
- Why never throw in an async callback? The try/catch has already exited; pass
cb(err).
Promises and async/await
1. Promise basics
- Pending, then fulfilled or rejected, exactly once
.thenhandles success,.catchrejection,.finallyalways runsasyncfunctions always return a promiseawaitpauses only that function; a rejection becomes a throw for try/catch
2. Combinators
Express Error Middleware
1. Definition and Mechanism
- Error handler has 4 params:
(err, req, res, next) - Found by arity: keep
nexteven if unused next(err)or a syncthrowskips to it- Register it last, after routes and
app.use
2. Express 4 vs 5
Unhandled Rejections and Uncaught Exceptions
1. What Fires
- unhandledRejection fires when a promise rejects with no handler attached
- Node 15+: default is crash with a non-zero exit
2. Last-Resort Hooks
| Event | Callback arg |
|---|
Environment Config and Graceful Shutdown
1. Env Config
process.envholds strings only- Local:
.envvia dotenv or--env-file; never commit it - Real values are set in the platform
- Fail fast at boot on missing vars
- Convert types:
Number(process.env.PORT) - Defaults only for non-secrets
2. Shutdown on SIGTERM
Cheat Sheet: Async, Errors and Shutdown
1. Callbacks and Promises
- Shape is
cb(err, result): check err first andreturn util.promisifyconverts it into a promise
| Method | Settles when |
|---|---|
Promise.all |
Check yourself
What logs first, and why? items.forEach(async id => await save(id)); console.log('done')
donelogs first: forEach ignores the promises its callbacks return- Fix:
for...ofwith await, orawait Promise.all(items.map(save))
Promise.all([a(), bFails(), c()]): what happens, and what would allSettled give instead?
- all rejects at once with b's error, and the results of a and c are lost