Error Handling and Graceful Shutdown in Node.js
Error handling in Node.js decides whether your server returns a clean 500 or crashes for everyone. Interviewers ask about async errors, unhandled rejections, operational versus programmer errors, and how to shut down without dropping requests.
What you will learn
- Separate operational errors from programmer errors
- Catch async errors correctly
- Handle unhandledRejection and uncaughtException
- Implement graceful shutdown on SIGTERM
Key concepts
Operational error
Expected failures in a correct program: invalid input, a timeout, a 404 from another service, a full disk. Handle them and return a useful response.
Programmer error
Bugs: reading a property of undefined, wrong argument types. You cannot recover safely, so log, return 500 and let the process restart if state may be corrupted.
unhandledRejection
A promise rejected with no catch. Since Node.js 15 this crashes the process by default. Always await or catch promises.
Graceful shutdown
On SIGTERM (sent by Kubernetes, Docker, PM2), stop accepting new connections, finish in-flight requests, close database pools, then exit.
Step by step
Custom error classes
export class AppError extends Error {
constructor(message, status = 500, code = 'INTERNAL') {
super(message)
this.status = status
this.code = code
}
}
export class NotFound extends AppError {
constructor(what) { super(what + ' not found', 404, 'NOT_FOUND') }
}Examples
Graceful shutdown
const server = app.listen(3000)
async function shutdown(signal) {
console.log(signal + ' received, shutting down')
server.close(async () => { // stop new connections, wait for open ones
await db.end()
await redis.quit()
process.exit(0)
})
setTimeout(() => process.exit(1), 10000).unref() // force after 10 s
}
process.on('SIGTERM', shutdown)
process.on('SIGINT', shutdown)
process.on('unhandledRejection', (err) => { logger.fatal(err); shutdown('unhandledRejection') })Practise it
Try these without looking back. If you can explain each one out loud, you are ready for this question.
- Throw inside an async Express 4 handler without next(err) and observe what happens; then fix it.
- Add a readiness endpoint that returns 503 while the server is shutting down.
Interview questions
What interviewers ask next on this topic. Answer out loud first, then open the model answer.
Should you keep the process running after uncaughtException?
No. After an uncaught exception the process may be in an unknown state (half-written data, held locks). Log it, stop taking traffic and exit; your process manager or orchestrator starts a fresh one.
How do you avoid dropping requests during a deploy?
Handle SIGTERM: fail the readiness probe so the load balancer stops sending traffic, call server.close() to finish in-flight requests, close pools, and exit before the orchestrator's grace period ends.
Summary
Handle operational errors with clear responses, treat programmer errors as bugs, never leave promises unhandled, and shut down gracefully on SIGTERM so deploys drop no requests.
Stuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus