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, then()
.
If a promise becomes rejected, and there are no rejection handlers to call (a handler can be attached through any of then()
, catch()
, or 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.
((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);
Promise.resolve().catch(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 synchronous throw
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.