一个异常处理程序,用于CLASS的所有异常

hus*_*ayt 21 c# exception

我有一个包含多个方法的类,并希望为它们提供一个异常处理程序.这些方法有很多,它们有不同的参数,为每个方法编写try/catch都会很难看.

你是否知道我可以通过拥有一个类的异常处理程序来完成它,这将处理它们.

更新:


很多人都问我为什么.原因是我用各种方法调用数据源.所以我的类有函数getData1,gedData2,getData3,getData4,....,getDataN.问题是无法检查连接是否仍处于打开状态,并且创建新连接非常昂贵.所以我试图重用连接,如果下次调用的连接失败,我会抓住这个并重新连接并再试一次.这就是为什么我需要这个try/catch所有块.

为所有功能执行此操作:

try{    
   datasource.getData()
}
catch(ConnectionException)
{
   datasource.Connect();
   datasource.getData()
}
Run Code Online (Sandbox Code Playgroud)

谢谢

Jac*_*lan 23

您可以使用委托将方法的代码传递到单个try catch中,如下例所示:

    private void GlobalTryCatch(Action action)
    {
        try
        {
            action.Invoke();
        }
        catch (ExpectedException1 e)
        {
            throw MyCustomException("Something bad happened", e);
        }
        catch (ExpectedException2 e)
        {
            throw MyCustomException("Something really bad happened", e);
        }
    }

    public void DoSomething()
    {
        GlobalTryCatch(() =>
        {
            // Method code goes here
        });
    }
Run Code Online (Sandbox Code Playgroud)

  • 很不错。如果该方法返回一个对象会是什么样子? (2认同)

Uta*_*aal 14

我无法找出任何理由为什么你可以使用单一方法处理类中的所有异常(你能详细说明吗?我好奇......)

无论如何,您可以使用AOP(面向方面​​编程)技术在类的方法周围注入(静态或运行时)异常处理代码.

有一个很好的汇编后处理库名为PostSharp,您可以使用类中方法的属性进行配置:

您可以定义这样的方面(来自PostSharp网站):

public class ExceptionDialogAttribute : OnExceptionAspect
{
    public override void OnException(MethodExecutionEventArgs eventArgs)
    {
        string message = eventArgs.Exception.Message;
        MessageBox.Show(message, "Exception");
        eventArgs.FlowBehavior = FlowBehavior.Continue;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您将该属性应用于要监视异常的方法,如下所示:

public class YourClass {

    // ...

    [ExceptionDialog]
    public string DoSomething(int param) {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

您还可以将该属性应用于整个类,如下所示:

[ExceptionDialog]
public class YourClass {
    // ...
    public string DoSomething(int param) {
        // ...
    }
    public string DoSomethingElse(int param) {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

这将把建议(异常处理代码)应用于类中的每个方法.

  • 好答案。仅供参考,看起来 PostSharp 将虚拟方法的 OnException 签名更改为 OnException(MethodExecutionArgs eventArgs) 。 (2认同)