Errors thrown from promises are handled by the second parameter (reject
) passed to then
or by the handler passed to catch
:
throwErrorAsync()
.then(null, error => { /* handle error here */ });
// or
throwErrorAsync()
.catch(error => { /* handle error here */ });
If you have a promise chain then an error will cause resolve
handlers to be skipped:
throwErrorAsync()
.then(() => { /* never called */ })
.catch(error => { /* handle error here */ });
The same applies to your then
functions. If a resolve
handler throws an exception then the next reject
handler will be invoked:
doSomethingAsync()
.then(result => { throwErrorSync(); })
.then(() => { /* never called */ })
.catch(error => { /* handle error from throwErrorSync() */ });
An error handler returns a new promise, allowing you to continue a promise chain. The promise returned by the error handler is resolved with the value returned by the handler:
throwErrorAsync()
.catch(error => { /* handle error here */; return result; })
.then(result => { /* handle result here */ });
You can let an error cascade down a promise chain by re-throwing the error:
throwErrorAsync()
.catch(error => {
/* handle error from throwErrorAsync() */
throw error;
})
.then(() => { /* will not be called if there's an error */ })
.catch(error => { /* will get called with the same error */ });
It is possible to throw an exception that is not handled by the promise by wrapping the throw
statement inside a setTimeout
callback:
new Promise((resolve, reject) => {
setTimeout(() => { throw new Error(); });
});
This works because promises cannot handle exceptions thrown asynchronously.
An error will be silently ignored if a promise doesn’t have a catch
block or reject
handler:
throwErrorAsync()
.then(() => { /* will not be called */ });
// error silently ignored
To prevent this, always use a catch
block:
throwErrorAsync()
.then(() => { /* will not be called */ })
.catch(error => { /* handle error*/ });
// or
throwErrorAsync()
.then(() => { /* will not be called */ }, error => { /* handle error*/ });
Alternatively, subscribe to the [unhandledrejection](<https://developer.mozilla.org/en-US/docs/Web/Events/unhandledrejection>)
event to catch any unhandled rejected promises: