小编Hai*_*ar 的帖子

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

我有一个类:

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块,即使只有一行代码.

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

c# exception-handling exception

8
推荐指数
2
解决办法
3970
查看次数

标签 统计

c# ×1

exception ×1

exception-handling ×1