Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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. 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. 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

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

inside the OnStart() of the Role. I was so focused on Azure that I supposed this couldn't work after all, that I didn't even try it :-)

like image 250
gumo Avatar asked Jan 07 '11 14:01

gumo


People also ask

Which function is involved when an unhandled exception is thrown?

7. Which function is invoked when an unhandled exception is thrown? Explanation: terminate() function is called/invoked incase any exception is not handled properly.

Which event is used for unhandled exceptions?

asax and the Application_Error event handler to execute code when an unhandled exception occurs.


1 Answers

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

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

inside the OnStart() of the Role.

like image 117
gumo Avatar answered Oct 31 '22 22:10

gumo