In a VSTO add-in you do not have an out-of-box solution to centralize exception handling like in a Windows Forms application.
To make sure that you catch every exception thrown by your code you would need to wrap every execution entry point, like application and user triggered events, inside a try/catch block. This would rapidly turns in a tedious task.
You can however resort to PostSharp to do all that heavy lifting for you at compile time and centralize the common exception logic in a single event as you would do with a AppDomain.UnhandledException if it were a desktop application.
For this I created a new PostSharp aspect to be associated to each execution entry point and a couple of other support classes. This error handling implementation is available from GitHub and can be placed in an independent class library or directly in the add-in project.
Having included the new PostSharp aspect you can then use it like illustrated in the following sample code:
using System; using System.Diagnostics; using Helpers.Vsto.ErrorHandling; using log4net.Config; using PostSharp.Laos; using Excel = Microsoft.Office.Interop.Excel; public partial class ThisAddIn { void ThisAddIn_Startup(object sender, EventArgs e) { // Ensure log4net configuration for error logging XmlConfigurator.Configure(); // Add unhandled exceptions handler ExecutionEntryPoint.UnhandledException += AddIn_Error; this.Application.WorkbookDeactivate += App_WorkbookDeactivate; this.Application.WorkbookNewSheet += App_WorkbookNewSheet; } void AddIn_Error(object sender, VstoUnhandledExceptionEventArgs e) { Type source = sender as Type; // Type where exception was thrown Debug.WriteLine(e.Exception.Message); } [ExecutionEntryPoint] void App_WorkbookDeactivate(Excel.Workbook Wb) { throw new InvalidOperationException("Ooops!"); } [ExecutionEntryPoint] void App_WorkbookNewSheet(Excel.Workbook Wb, object Sh) { throw new InvalidOperationException("D'oh!"); } // Remaining Add-in code ... }
Hi Joao,
I’ve not come across Postsharp before; and must ask: will your proposed solution work with the free Express version?
Thanks,
James.
Hi James,
yes you should be fine with the PostSharp Express version. I haven’t revisited PostSharp recently but judging from their site, the available features on the free version seem to cover all the requirements of the solution proposed.
Awesome – you’ve saved me a load of time thank you very much!
Will go ahead with my own investigations with confidence.
So once I got my head round it this working well, exactly how I want it.
Many thanks – & thanks for introducing me to aspect oriented programming.