如何在CSharp中捕获类级别的所有异常?

Hai*_*ar 8 c# exception-handling exception

我有一个类:

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,您可以看到在每个方法(MethodA,MethodB,MethodC)中都有try ... catch块来记录错误,然后抛出更高级别.

想象一下,当我的Repository类可能有超过一百个方法时,在每个方法中我都尝试了... catch块,即使只有一行代码.

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

Sou*_*tra 6

当有免费 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
    }
}
Run Code Online (Sandbox Code Playgroud)

ExceptionWrapper在类上添加属性可确保所有属性和方法都封装在try/catch块中.catch中的代码将是您在ExceptionWrapper中的覆盖函数OnException()中放入的代码.

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


Llo*_*oyd 1

你太防守了。不要过度使用,try..catch只在需要的地方使用它。

在这种情况下,请考虑捕获通过与类外部的类交互而引发的异常。请记住,例外情况将会被传播。