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()
.
catch()
internally calls then()
. 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() {});
Note: The examples below are throwing instances of Error. This is considered good practice in contrast to throwing Strings; 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 like stack traces.