I have a Flow Controller
like method in NestJS/TypeScript.
Let me copy paste the method here (with some changes):
async my_flow_implementation(....) {
checkIfCanbeDeleted = some_method(...);
if (checkIfCanbeDeleted) {
step1_status = await step1_execution(..);
step2_status = await step2_execution(..);
........
stepn_status = await stepN_execution(..);
}
}
Now any of this stepN_execution(...) can potentially fail. And based on the type of failure we may want to do some code handling and proceed with the next step. But the failure of a particular step should not interrupt the whole flow.
Something like (just a snippet):
step1_status = await step1_execution(..);
if (step1_status == FAILURE) {
// Do some handling ..
// _but_ continue with next step
}
So one solution, naively, I am thinking as :
try {
step1_status = await step1_execution(..);
} catch (error1) {
// handle error
try {
step2_status = await step2_execution(..);
} catch (error2) {
try {
step3_status = await step3_execution(..);
} catch (error3) {
...........
}
}
}
But it looks pretty right-drifted code, not elegant.
What is my alternative here?
Any pseudu code/idea will help (as it's a project, can't fully share the code).
CodePudding user response:
You can use the .catch()
callback of the promise.
Here is an example:
let step1_status = await someFunction().catch((error) => {
/* Do error handling */
});
let step2_status = await someFunction().catch((error) => {
/* Do error handling */
});
let step3_status = await someFunction().catch((error) => {
/* Do error handling */
});