Errors, memory and request context · core
Error handling in Node
Separate operational errors (expected failures like a timeout or bad input, which you handle and report) from programmer errors (bugs, which you log and then crash and restart on), and handle every promise rejection, because an unhandled rejection crashes Node by default.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Operational errors: network timeouts, DB down, invalid input, not found. Handle them, return a clear error, maybe retry. Programmer errors: TypeError, reading a property of undefined. Fix the code; after an uncaught exception the process state is unknown.
- try/catch catches synchronous throws and awaited rejections only. It does not catch errors thrown later inside a callback (setTimeout, event listeners, old callback APIs).
- Since Node 15 the default --unhandled-rejections mode is 'throw': an unhandled rejection becomes an uncaught exception and the process exits with code 1, unless an 'unhandledRejection' handler exists.
- process.on('uncaughtException') is for logging and a clean exit, not for carrying on. A supervisor (Kubernetes, ECS, PM2, systemd) restarts the process.
- Error-first callbacks: callback(err, result). Check err first and return.
- Add context without losing the original: new Error('Failed to load user', { cause: err }). AggregateError holds many errors (Promise.any rejects with one).
- Prefer process.exitCode = 1 over process.exit(1) so pending output and handles can finish.
- Fire-and-forget promises (analytics, emails after responding) need their own .catch.
The red pen
Common traps: mistake → fix
Mistake: try/catch around setTimeout catches the error inside it
Fix: the callback runs later on a new stack; the try block has already finished.
Mistake: An unhandled rejection only prints a warning
Fix: since Node 15 it crashes the process by default.
Mistake: Catch uncaughtException and keep serving
Fix: state may be corrupted; log, shut down gracefully and let the supervisor restart.
Easy to hard
Questions interviewers ask, easy to hard
- How do you handle errors in Node: sync code, callbacks, promises?
- What is an unhandled promise rejection and what does Node do with it today?
- Operational vs programmer errors: examples, and how you treat each.
- Should you use process.on('uncaughtException') to keep the server alive?
- How do you make sure errors in background work are not lost?
Practise
Practise with these questions
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.