Unhandled Exceptions Cause the Instance to Recycle
If you have an unhandled exception in your code the Windows Azure instance will recycle, tearing down the application domain and restart the instance. Unhandled exceptions are all exceptions that not caught with a try/catch by your code.
You can Write You Exceptions to Storage with Windows Azure Diagnostics
Windows Azure Diagnostics enables you to collect diagnostic data from an application running in Windows Azure. If you catch the unhandled exceptions in an overridden Run() method of the RoleEntryPoint class using a try/catch, you can write those exceptions to Windows Azure Diagnostics using the Trace class. Once they are written you can throw the Exception causing the role to recycle.
The Minimum Transfer Schedule of Windows Azure Diagnostics is 1 Minutes
Windows Azure Diagnostics writes the diagnostic data to local storage (local to the instance) and then transfers it to Windows Azure Storage at a scheduled interval. Part of configuring diagnostics is setting the ScheduledTransferPeriod. The minimum interval is 1 minutes from the start of the start of the instance. There are several things you should be aware of with this design:
- If your worker role instance encounters an unhandled exception and logs it, and then recycles the next time it starts for longer than the scheduled transfer period the exception from the previous instantiation will be written to the Windows Azure Storage.
- If your work role continually recycles from unhandled exceptions before it can reach at least the scheduled transfer period your exceptions logged in local storage will not appear in Windows Azure storage.
- If the instance is recycled and doesn’t start in the same location, the exceptions written to the local storage that have not be transferred to Windows Azure Storage will be lost. This might happen in the case of a hardware failure where the instances need to be moved to a different location.
- Exceptions that are logged do not show up instantly in Windows Azure Storage.
You Do Not Have To Throw the Exceptions that You Catch
Some exceptions like: OutofMemoryException should cause the instance to recycle. However, some exceptions like those derived from InvalidOperationException, can be caused when you have an error writing to Windows Azure Storage – these can just be logged. Not recycling allows Windows Azure Diagnostics to write the exception to Windows Azure Storage faster – since the scheduled transfer period isn’t reset.
I create a method that performs a litmus test on the caught exceptions and then determines if I want to throw them or not. Because this will vary from application to application you will have to develop your own litmus method. Using the C# operator is will simplify this task.