如何在类级别捕获所有异常

本文关键字:异常 | 更新日期: 2023-09-27 17:49:53

我有一个类:

class SampleRepositoryClass
{
    void MethodA()
    {
        try
        {
            //do something
        }
        catch(Exception ex)
        {
            LogError(ex);
            throw ex;
        }        
    }
    void MethodB(int a, int b)
    {
        try
        {
            //do something
        }
        catch(Exception ex)
        {
            LogError(ex);
            throw ex;
        }
    }
    List<int> MethodC(int userId)
    {
        try
        {
            //do something
        }
        catch(Exception ex)
        {
            LogError(ex);
            throw ex;
        }
    }
}

在上面的例子中,你可以看到在每个方法(MethodA, MethodB, MethodC)中都有try…Catch块记录错误,然后将其抛出到更高的级别。

想象一下,当我的Repository类可能有超过100个方法,并且在每个方法中我都尝试…Catch块,即使只有一行代码。

现在,我的目的是减少这些重复的异常日志代码,并在类级别而不是方法级别记录所有异常。

如何在类级别捕获所有异常

既然有FREE Post Sharp Express这样的东西,为什么还要重新发明轮子呢?这就像添加PostSharp.dll作为项目的引用一样简单。这样做之后,您的存储库看起来如下所示:

[Serializable]
class ExceptionWrapper : OnExceptionAspect
{
    public override void OnException(MethodExecutionArgs args)
    {
        LogError(args.Exception);
        //throw args.Exception;
    }
}
[ExceptionWrapper]
class SampleRepositoryClass
{
    public void MethodA()
    {
        //Do Something
    }
    void MethodB(int a, int b)
    {
        //Do Something
    }
    List<int> MethodC(int userId)
    {
        //Do Something
    }
}

在类上添加ExceptionWrapper属性,确保所有属性和方法都封装在try/catch块中。catch中的代码将是放在ExceptionWrapper中重写函数OnException()中的代码。

你也不需要编写代码来重新抛出。如果提供了正确的流行为,也可以自动重新抛出异常。

你太戒备了。不要过度使用try..catch,只在你需要的地方捕捉它。

在这种情况下,考虑捕捉通过在类之外与类交互而抛出的异常。请记住,异常将被传播。

使用诸如Policy Injection Application Block, Castle, Spring之类的库。净等。这些库允许你注入异常捕获行为。

只需在 app . xml .cs中实现DispatcherUnhandledException;它将处理你所有的异常;

    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            DispatcherUnhandledException += App_DispatcherUnhandledException;
        }
        void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            LogError(e);
// MessageBox.Show(e.Exception.Message);
            e.Handled = true;
        }