JSFiddle - React, Tailwind, and code Playground
HTML
Look in the console.
JavaScript
const cif = (predicate, handler) => e => {
if (predicate(e)) {
return handler(e);
}
throw e;
};
// Usage
class ValidationError extends Error { }
class InternalError extends Error { }
const handleValidationError = e => {
console.error("ValidationError", e);
};
const handleInternalError = e => {
console.error("InternalError", e);
};
const handleOtherErrors = e => {
console.error("Other Error", e);
};
const somePromise = new Promise((_, reject) => {
setTimeout(reject, 0, new InternalError());
});
somePromise
.catch(cif(reason => reason instanceof ValidationError, reason => handleValidationError(reason))) // handle ValidationErrors
.catch(cif(reason => reason instanceof InternalError, reason => handleInternalError(reason))) // handle InternalErrors
.catch(cif(reason => handleOtherErrors(reason))); // catch all others