error-handling
unhandledrejection event
Fires when a promise rejects and has no rejection handler attached by the end of the current microtask cycle. Provides a last-chance hook to log or report the error before the runtime warns or exits.
window.addEventListener('unhandledrejection', handler) // Node: process.on('unhandledRejection', handler) Parameters
| Parameter | Purpose |
|---|---|
| event.reason | The rejection reason (browser event) |
| event.preventDefault() | Suppress the default warning in browsers |
| Node: (reason, promise) | Node passes reason and the rejected promise |
Examples
window.addEventListener('unhandledrejection', event => {
console.error('Unhandled:', event.reason);
event.preventDefault();
}); Browser global handler for stray promise rejections.
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection:', reason);
}); Node.js equivalent — since Node 15 unhandled rejections crash the process by default.
// Triggers the event
Promise.reject(new Error('lost'));
// (No .catch anywhere, so unhandledrejection fires) Attaching a .catch later within the same microtask cancels it via 'rejectionhandled'.
Gotcha
Node 15+ crashes on unhandled rejections by default — always attach a handler in production. This is a safety net, not a substitute for local .catch or try/catch.
Related
.catch()
Attaches a rejection handler to a promise chain, equivalent to .then(undefined, onRejected). Returns a new promise that fulfills with the handler's return value, letting you recover from errors.
try / catch with await
Since await throws when the awaited promise rejects, standard try/catch is the idiomatic way to handle async errors inside an async function. A finally block runs on both success and failure paths.
Promise.reject
Returns a promise that is already rejected with the given reason. Useful for early-exit paths in functions that must always return a promise.
← All JS Promise reference · async/await vs promises vs callbacks