How do you implement a global error handler for uncaught exceptions in Node.js?

Question

Grade: Education Subject: Support
How do you implement a global error handler for uncaught exceptions in Node.js?
Asked by:
79 Viewed 79 Answers

Answer (79)

Best Answer
(351)
You can use `process.on('uncaughtException', (err) => { ... })`. This event listener will execute whenever an exception is thrown but not caught within a `try...catch` block or within a promise's `.catch()` handler. Inside the handler, you typically log the error, potentially clean up resources, and decide whether to terminate or attempt to recover.