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开发者_StackOverflow 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 :-)
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.
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.
The other alternative is that there is no exception.
精彩评论