Error Handling in Promises
A promise reports failure by being rejected, and a catch() callback receives the reason. Errors thrown inside a promise’s executor or inside a then() callback become rejections automatically, so one catch() at the end of a chain can handle every failure in it.
The rules differ from synchronous code in a few ways that catch people out, so this page covers how errors travel and where they can escape.
A throw becomes a rejection
Section titled “A throw becomes a rejection”An error thrown while the executor is running rejects the promise, just as calling reject would. Here JSON.parse() throws on the second, malformed order:
const parseOrder = (text) => new Promise((resolve) => { resolve(JSON.parse(text)); });
parseOrder('{"id": 7}') .then((order) => console.log('Order', order.id)) .catch((error) => console.log(error.name));
parseOrder('{id: 7}') .then((order) => console.log('Order', order.id)) .catch((error) => console.log(error.name));This prints:
Order 7SyntaxErrorErrors skip ahead to the next catch()
Section titled “Errors skip ahead to the next catch()”A rejection, or an error thrown in a then() callback, skips every then() callback after it and goes to the next catch(). What that catch() returns becomes a normal value again, so the chain carries on after it:
Promise.resolve(['milk', 'eggs']) .then((items) => { if (!items.includes('bread')) { throw new Error('The list has no bread'); } return items; }) .then((items) => console.log('This step is skipped', items)) .catch((error) => { console.log('Recovered from:', error.message); return []; }) .then((items) => console.log(`Carrying on with ${items.length} items`));This prints:
Recovered from: The list has no breadCarrying on with 0 itemsTo pass the failure on instead of recovering, throw again inside the catch() callback. Rejecting with an Error object, rather than a string or a number, gives the handler a message and a stack trace to work with.
try…catch does not see a rejection
Section titled “try…catch does not see a rejection”A try...catch block catches errors only while its own code is running. A promise is rejected later, after the block has finished, so the rejection goes past it:
try { Promise.reject(new Error('Disk full')).catch((error) => { console.log('catch() handled it:', error.message); }); console.log('The try block has finished');} catch (error) { console.log('try...catch handled it:', error.message);}This prints:
The try block has finishedcatch() handled it: Disk fullInside an async function the position is different, because await throws the rejection where the function is waiting, so a try...catch around the await does catch it. Async/Await combined with Promises shows this.
The second argument of then()
Section titled “The second argument of then()”then() accepts a failure callback as its second argument, but that callback does not catch an error thrown by the success callback beside it. A catch() placed afterwards does:
const onSuccess = (value) => { throw new Error(`Could not use ${value}`);};const onFailure = (error) => console.log('Handled:', error.message);
Promise.resolve('the first value') .then(onSuccess, onFailure) .catch((error) => console.log('Only a later catch() sees:', error.message));
Promise.resolve('the second value').then(onSuccess).catch(onFailure);This prints:
Only a later catch() sees: Could not use the first valueHandled: Could not use the second valuePitfall: throwing inside a callback in the executor
Section titled “Pitfall: throwing inside a callback in the executor”An error thrown inside a timer or event callback is not part of the executor’s run, because the executor finished long before. The promise is never rejected, and the error escapes as an uncaught exception. This version does not work:
const loadLater = () => new Promise((resolve, reject) => { setTimeout(() => { throw new Error('Load failed'); }, 50); });
loadLater().catch((error) => console.log('Caught:', error.message));Node stops the program with the uncaught error, and a browser reports it in the console, while the catch() callback never runs. Calling reject in the callback fixes it:
const loadLater = () => new Promise((resolve, reject) => { setTimeout(() => { reject(new Error('Load failed')); }, 50); });
loadLater().catch((error) => console.log('Caught:', error.message));This prints:
Caught: Load failedUnhandled rejections
Section titled “Unhandled rejections”A rejected promise with no catch() anywhere along its chain is an unhandled rejection. Node treats one as a fatal error and stops the program. Browsers log it in the console and fire an unhandledrejection event on window, which a page can listen to in order to report errors it missed. End every chain with a catch(), or await it inside a try...catch, so that no rejection goes unhandled.
Steve Griffith covers this topic in his video Error Handling in Promises.