Node.js
Unhandled rejection
Learn unhandled rejection and uncaughtException.
Unhandled rejection
When a Promise is rejected and there is no .catch() attached, an unhandled rejection occurs. Node.js reports this with the process.on("unhandledRejection", cb) event.
For example, Promise.reject(new Error("failed")) with no .catch() fires the unhandledRejection event. The callback receives the rejected value through the reason parameter. In Node.js 15+ an unhandled rejection terminates the process by default, so defining a global handler is important. With reason.name you can print, log or track the error type. This way the app does not crash silently; the error is recorded.
uncaughtException
An uncaughtException is an error in synchronous code that is not caught by try/catch. It is listened to with process.on("uncaughtException", cb). When this event fires, the app is already in an unstable state.
For example, if throw new Error("boom") is thrown outside a try/catch, uncaughtException fires. Node.js recommends terminating the process after this event, because the app's state is uncertain. Usually the error is logged and the process is restarted (for example with PM2 or systemd). unhandledRejection is for Promise rejections. Listening to both is important in production apps so errors are not lost. This sets up a monitoring and restart chain.
Exercise Add an unhandledRejection handler
Add a handler with process.on("unhandledRejection", (reason) => { ... }); print console.log(reason.name). Trigger a rejection with Promise.reject(new Error("test")). The setTimeout(() => {}, 100) is already in the starting code.
Show example solution
process.on("unhandledRejection", (reason) => {
console.log(reason.name);
});
Promise.reject(new Error("test"));
Test yourself
-
Complete the unhandledRejection event
process.on("____", (reason) => { console.log(reason.name); });
Show answer
process.on("unhandledRejection", (reason) => { console.log(reason.name); });
-
Which event catches an unhandled Promise rejection?
process.on("?", cb)
- uncaughtException
- exit
- warning
- unhandledRejection
Show answer
unhandledRejection — unhandledRejection fires for rejected promises with no .catch().
-
Match each event to its source
- unhandledRejection
- Promise rejection
- uncaughtException
- Synchronous error
- process.on
- Listens for an event
- setTimeout
- Provides a wait
Next lesson: Summary - Error handling