Promise.prototype.catch()
The catch()
method of a Promise
object schedules a function to be called when the promise is rejected. It immediately returns an equivalent Promise
object, allowing you to chain calls to other promise methods. It is a shortcut for Promise.prototype.then(undefined, onRejected)
.
Syntax
catch(onRejected)
catch((reason) => {
// rejection handler
})
Parameters
onRejected
- : A
Function
called when thePromise
is rejected. This function has one parameter: the rejection reason.
- : A
Return value
Returns a new Promise
. This new promise is always pending when returned, regardless of the current promise's status. It's eventually rejected if onRejected
throws an error or returns a Promise which is itself rejected; otherwise, it's eventually fulfilled.
Description
The catch
method is used for error handling in promise composition. Since it returns a Promise
, it can be chained in the same way as its sister method, Promise.prototype.then()
.
If a promise becomes rejected, and there are no rejection handlers to call (a handler can be attached through any of Promise.prototype.then
, Promise.prototype.catch
, or Promise.prototype.finally
), then the rejection event is surfaced by the host. In the browser, this results in an unhandledrejection
event. If a handler is attached to a rejected promise whose rejection has already caused an unhandled rejection event, then another rejectionhandled
event is fired.
catch()
internally calls then()
on the object upon which it was called, passing undefined
and onRejected
as arguments. The value of that call is directly returned. This is observable if you wrap the methods.
// overriding original Promise.prototype.then/catch just to add some logs
((Promise) => {
const originalThen = Promise.prototype.then;
const originalCatch = Promise.prototype.catch;
Promise.prototype.then = function (...args) {
console.log("Called .then on %o with arguments: %o", this, args);
return originalThen.apply(this, args);
};
Promise.prototype.catch = function (...args) {
console.error("Called .catch on %o with arguments: %o", this, args);
return originalCatch.apply(this, args);
};
})(Promise);
// calling catch on an already resolved promise
Promise.resolve().catch(function XXX() {});
// Logs:
// Called .catch on Promise{} with arguments: Arguments{1} [0: function XXX()]
// Called .then on Promise{} with arguments: Arguments{2} [0: undefined, 1: function XXX()]
This means that passing undefined
still causes the returned promise to be rejected, and you have to pass a function to prevent the final promise from being rejected.
Because catch()
just calls then()
, it supports subclassing.
Note: The examples below are throwing instances of
Error
. As with synchronousthrow
statements, this is considered a good practice; otherwise, the part doing the catching would have to perform checks to see if the argument was a string or an error, and you might lose valuable information such as stack traces.