Unhandled rejection
- Node.js course
- Intermediate
- Lesson 80/116
- 5 min
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.
Practice 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.
Starter code
// Add an unhandledRejection handler — print reason.name
// write here
// Create a rejected promise
// write here
// Wait so the handler can fire
setTimeout(() => {}, 100);Sample solution
process.on("unhandledRejection", (reason) => {
console.log(reason.name);
});
Promise.reject(new Error("test"));Expected output
Error
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the unhandledRejection event
process.on("____", (reason) => { console.log(reason.name); });
process.on("unhandledRejection", (reason) => { console.log(reason.name); });
Explanation: The unhandledRejection event catches Promise rejections.
2 Which event catches an unhandled Promise rejection?
process.on("?", cb)- uncaughtException
- exit
- warning
- unhandledRejection Correct answer
Explanation: unhandledRejection fires for rejected promises with no .catch().
3 Match each event to its source
| Term | Meaning |
|---|---|
unhandledRejection |
Promise rejection |
uncaughtException |
Synchronous error |
process.on |
Listens for an event |
setTimeout |
Provides a wait |