Is it possible to combine multiple identical catch blocks?
Yes, you can if you chain your promises by returning the inner promise from within the .then()
handler and then let reject propagation bubble up to a single .catch()
block:
replace(replaceOptions(dirPath + '/' + jsName)).then((changes) => {
fileModifiedPrint(changes);
removeDocumentation(jsName, dirPath, dirName);
// return this promise to chain it to the parent promise
return replace(replaceHTMLID(dirPath + '/' + jsName)).then((changes) => {
// do whatever you want here
});
}).catch((err) => {
// this will catch any rejection anywhere in the promise chain
// that wasn't already caught by someone
fileErrorPrint(jsName, dirPath, err, "write");
});
When you chain promises, a rejected promise will propagate back up to the chain to the first .catch()
handler in the chain that it encounters. If there is no .catch()
handler until the top level, then it will go all the way up to that .catch()
. This allows you to either handle a rejection locally and "hide" it from the rest of the chain or to let it reject the whole chain by letting it propagate up. You can implement either type of logic depending upon what is most appropriate for your particular situation.
FYI, you can also un-nest your .then()
on the inner replace()
too like this:
replace(replaceOptions(dirPath + '/' + jsName)).then((changes) => {
fileModifiedPrint(changes);
removeDocumentation(jsName, dirPath, dirName);
// return this promise to chain it to the parent promise
return replace(replaceHTMLID(dirPath + '/' + jsName));
}).then((changes) => {
// results of the second `replace()` call.
// do whatever you want here
}).catch((err) => {
// this will catch any rejection anywhere in the promise chain
// that wasn't already caught by someone
fileErrorPrint(jsName, dirPath, err, "write");
});