How would you implement different types of errors, so you\'d be able to catch specific ones and let others bubble up..?
One way to achieve this is to modify the
I didn't love any of these solutions so I made my own. The try-catch-finally.js is pretty cool except that if you forget one little underscore (_) before the try then the code will still run just fine, but nothing will get caught ever! Yuck.
I added a CatchFilter in my code:
"use strict";
/**
* This catches a specific error. If the error doesn't match the errorType class passed in, it is rethrown for a
* different catch handler to handle.
* @param errorType The class that should be caught
* @param funcToCall The function to call if an error is thrown of this type
* @return {Function} A function that can be given directly to the `.catch()` part of a promise.
*/
module.exports.catchOnly = function(errorType, funcToCall) {
return (error) => {
if(error instanceof errorType) {
return funcToCall(error);
} else {
// Oops, it's not for us.
throw error;
}
};
};
Now I can filter like in C# or Java:
new Promise((resolve, reject => {
}).catch(CatchFilter.catchOnly(MyError, err =>
console.log("This is for my error");
}).catch(err => {
console.log("This is for all of the other errors.");
});