jeudi 21 juillet 2016

Interrupting long running method pattern

I am currently using this somewhat tedious pattern to generate error message for user running some long operation:

string _problem;

void SomeLongRunningMethod()
{
    try
    {
        _problem = "Method1 had problem";
        Method1();
        _problem = "Unexpected error during doing something in Method2";
        if(Method2())
        {
            _problem = "Method3 fails";
            Method3();
        }
        _problem = "Not possible to obtain data";
        var somedata = Method4();
    }
    catch(Exception)
    {
        MessageBox.Show("Problem with some long running method: " + _problem);
    }
}

Either of methods may throw and I want to tell the user at which step failure occurs. This is done by setting _problem before running any of them.

In some cases I can use different Exception types to catch, but that doesn't works always, e.g. both Method1 and Method2 can throw InvalidOperationException().

This repeated code looks like a pattern. Though I can't recognize it. Any ideas? How to improve readability?

Aucun commentaire:

Enregistrer un commentaire