Sometimes I have a code in try-catch-finally block when finally
branch does some cleanup code which may throw an Error
. An error in the finally
branch suppresses a possible error in the main branch. I want exactly the opposite: see an error from the main branch always and an error from the finally
branch only when the main branch proceeds without an error. I have came up with solution:
let thrownError = false;
try {
doMainCode();
} catch (err) {
thrownError = true;
throw err;
} finally {
try {
doCleanUpCode();
} catch (err) {
if (!thrownError)
throw err;
console.error("Suppressed finally error", err);
}
}
Which is cumbersome. Is there any simpler way how to change error precedence in try-catch-finally block?