Design pattern / C# trick for repeated bit of code

2019-04-05 23:12发布

I have a WCF service which logs any exceptions and then throws them as FaultExceptions.

I am doing a lot of repetition e.g. in each service method.

try { 
   // do some work

}
catch(Exception ex)
{
  Logger.log(ex);

  // actually will be Fault Exception but you get the idea.
  throw ex;
}

I am looking for a more elegant way to do this as I am cutting and pasting the try/catch throughout each service.

Is there a design pattern /C# trick that could be used to make this more elegant?

9条回答
该账号已被封号
2楼-- · 2019-04-05 23:31

We have a similar problem in one of our WCF services, which I've solved by using a helper delegate:

public static void ErrorHandlingWrapper(Action DoWork)
{
    try { 
        DoWork();
    }
    catch(Exception ex)
    {
        Logger.log(ex);

        // actually will be Fault Exception but you get the idea.
        throw;
    }
}

Usage:

public void MyMethod1()
{
    ErrorHandlingWrapper(() => {
        // do work
    });
}

public void MyMethod2()
{
    ErrorHandlingWrapper(() => {
        // do work
    });
}

You still have to repeat the wrapper, but that's a lot less code and you can modify the logic in the try..catch in one place.

查看更多
小情绪 Triste *
3楼-- · 2019-04-05 23:31

If your question is about how to make your current pattern faster for you to work with you can repeat that boiler plate code by creating a Snippet

<CodeSnippets
    xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <CodeSnippet Format="1.0.0">
        <Header>
            <Title>
                trylog
            </Title>
            <Shortcut>
                trylog
            </Shortcut>
        </Header>
        <Snippet>
            <Code Language="CSharp">
                <![CDATA[try { 
   // do some work

}
catch(Exception ex)
{
  Logger.log(ex);

  // actually will be Fault Exception but you get the idea.
  throw ex;
}]]>
            </Code>
        </Snippet>
    </CodeSnippet>
</CodeSnippets>
查看更多
Ridiculous、
4楼-- · 2019-04-05 23:38

You may want to try AspectF (not mine): http://www.codeproject.com/Articles/42474/AspectF-Fluent-Way-to-Add-Aspects-for-Cleaner-Main. It's by Omar Al-Zabir... creator of Dropthings framework, amongst other things. Hope this helps you.

查看更多
登录 后发表回答