2014-03-13 28 views
7

我有一个类,如:如何捕获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; 
     } 
    } 
} 

在上面的例子中,你可以看到,在每一个方法(治法,方法b,MethodC)已经尝试... catch块来记录错误,然后扔至更高水平。

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

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

+2

只有[面向方面的编程](http://en.wikipedia.org/wiki/Aspect-oriented_programming)工具/织工[像PostSharp](http://www.postsharp.net/)可以帮助你。顺便说一下,在一个类中有超过一百种方法?这只是... *不好*。至少从我的角度来看。而且绝对可怕。 –

+0

这是真的,但我的业务和存储库类有许多方法,使这些类太重。实际上,类中方法的数量取决于业务规则的复杂性或您想要执行的操作的数量。 – Haidar

+2

请勿使用“throw ex;”因为这会破坏你宝贵的调用堆栈。只需写下“扔”;并且异常中的信息将被保留。有了这个说法,我想指出,除非你知道如何处理它们,否则你不应该发现异常。参考:http://stackoverflow.com/questions/730250/is-there-a-difference-between-throw-and-throw-ex –

回答

1

你太防守了。不要过度使用try..catch只有在你需要需要它。

在这种情况下,考虑捕捉异常情况下与您班级以外的班级进行交互引发的异常。记住例外将被传播。

1

使用库,如策略注入应用程序块,城堡,Spring.NET等。这些库允许你注入行为作为例外捕获。

+0

请不要使用任何其他库(策略注入应用程序块,Castle或Spring.NET)共享一些示例代码? – Haidar

+0

不幸的是,这些库实现代理设计模式,并处理了很多反射等。如果我跳过这个管道,我将不得不编码很多... –

0

Just implement DispatcherUnhandledException in you App.xaml.cs;它会处理你所有的例外;

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; 
     } 
+0

对不起,Jannesary,我想在BAL或DAL的类库中执行它。 – Haidar

5

为什么要重新发明轮子,当有这样的事,作为免费邮政快递夏普。 这与将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中的overriden函数OnException()中放置的代码。

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