Disclaimer
In the following post:
action
= Action
/Func
I have a long method that does multiple actions(s).Each action is wrapped in a try-catch
.If the specific action fails , in the catch
i must perform a clear
action for all previous ones and the current one. I do not know a way to stop duplicating code in the catch
and aggregate them using a design pattern or something.
What i have currently
public void LongMethod()
{
try
{
try
{
action1();
}catch(Exception ex)
{
ClearAction1();
}
try{
action2();
}catch(Exception ex){
Clearaction1();
Clearaction2();
}
try
{
action3();
}
catch(Exception ex)
{
Clearaction1();
Clearaction2();
Clearaction3();
}
catch(Exception ex)
{
//how should i aggregate the action clearance here
}
}
In the above method i do not want to write in all catch blocks all the clear
actions up until that point. I would like for each successful action to set something like a checkpoint , and then when that fails , check the state
and perform all required clearing up until that point.
What i would like
public void LongMethod()
{
try
{
int checkpoint=0;
action1();
checkpoint=1;
action2();
checkpoint=2;
action3();
checkpoint=3;
action4(); //fails here
}
catch(Exception ex)
{
switch(checkpoint)
{
3//does Clearaction1()+Clearaction2()+Clearaction3()+Clearaction4();
}
}
}
I was thinking if there is something like a design pattern to wrap each of these actions
which might have different return types and pipeline them.Whichever actionN
fails it triggers Clearaction1()
...ClearactionN()
where N is the Action
that did fail.
P.S It might be something like a monad
.
m a ->(a->m b) -> m b
-> (m b -> (b -> m c) -> m c)
-> (m c -> ( c -> m d) -> m d)
where a
,b
,c
,d
are types the difference being that i need to aggregate all failure treatment.
Aucun commentaire:
Enregistrer un commentaire