简体   繁体   English

如何在Windows Azure(工作器)角色中捕获未处理的异常

[英]How to catch an unhandled exception in Windows Azure (Worker) Role

I'm trying to catch all unhandled exceptions in my worker role. 我正试图捕捉我的工作角色中所有未处理的异常。 I tried putting a try - catch block into the Run() method (as suggested here ) but with no success. 我尝试将一个try - catch块放入Run()方法(如此处所示 ),但没有成功。

public override void Run()
{
  try
  {
    base.Run();
  }
  catch (Exception ex)
  {
    Trace.TraceError("Unhandled Exception: {0}", ex);    
    throw ex;
  }
}

The role hosts a WCF service, so there is no other logic inside the Run() method. 该角色承载WCF服务,因此Run()方法中没有其他逻辑。 Is there another possibility to catch exceptions at this level? 还有另一种可能性来捕获此级别的异常吗?

Update 1 To clarify the problem: The role self hosts a WCF service (initialized in OnStart() ) where some operations are background operations. 更新1澄清问题:角色self托管WCF服务(在OnStart()初始化),其中某些操作是后台操作。 When the service is called and that method throws an unexpected exception, I like to catch that to write it to the log. 当调用该服务并且该方法抛出意外异常时,我想抓住它将其写入日志。

Solution: Obviously it is like in a normal C# application: Just add a handler to the UnhandledException event like this 解决方案:显然它就像在普通的C#应用​​程序中一样:只需像这样向UnhandledException事件添加一个处理程序

AppDomain.CurrentDomain.UnhandledException +=
  new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

inside the OnStart() of the Role. 在角色的OnStart()内部。 I was so focused on Azure that I supposed this couldn't work after all, that I didn't even try it :-) 我是如此专注于Azure,我认为这毕竟不起作用,我甚至没有尝试过:-)

As already updated in my question, here for completeness's sake as answer: 正如我在问题中已经更新的那样,这里为了完整性而作为答案:

Obviously it is like in a normal c# application: Just add a handler to the UnhandledException event like this 显然它就像在普通的c#应用程序中一样:只需像这样向UnhandledException事件添加一个处理程序

AppDomain.CurrentDomain.UnhandledException +=
   new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

inside the OnStart() of the Role. 在角色的OnStart()内部。

The catch will catch all exceptions. 捕获将捕获所有异常。

You are throwing it again so that one will not be caught. 你再扔它,这样就不会被抓住。

Also you are logging, but logs are not turned on by default in Azure, since they cost. 您也在进行日志记录,但Azure中默认情况下不会打开日志,因为它们会花费。

The other alternative is that there is no exception. 另一种选择是没有例外。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM