Created
February 17, 2010 21:25
-
-
Save jmangelo/307022 to your computer and use it in GitHub Desktop.
Helpers classes for centralized exception handling in a VSTO add-in using PostSharp.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using log4net; | |
using PostSharp.Laos; | |
// http://exceptionalcode.wordpress.com/2010/02/17/centralizing-vsto-add-in-exception-management-with-postsharp/ | |
namespace Helpers.Vsto.ErrorHandling | |
{ | |
[Serializable] | |
public sealed class ExecutionEntryPointAttribute : OnExceptionAspect | |
{ | |
private const string DefaultLogMessage = "Unhandled exception."; | |
public ExecutionEntryPointAttribute() | |
: this(true, true) | |
{ | |
} | |
public ExecutionEntryPointAttribute(bool triggerEvents, bool logExceptions) | |
:this (true, true, DefaultLogMessage) | |
{ | |
} | |
public ExecutionEntryPointAttribute(bool triggerEvents, bool logExceptions, string logMessage) | |
{ | |
this.TriggerEvents = triggerEvents; | |
this.LogExceptions = logExceptions; | |
this.LogMessage = logMessage; | |
} | |
public bool TriggerEvents { get; set; } | |
public bool LogExceptions { get; set; } | |
public string LogMessage { get; set; } | |
public override void OnException(MethodExecutionEventArgs eventArgs) | |
{ | |
Type source = eventArgs.Method.DeclaringType; | |
if (this.LogExceptions) | |
{ | |
ILog log = LogManager.GetLogger(source); | |
log.Fatal(this.LogMessage, eventArgs.Exception); | |
} | |
if (this.TriggerEvents) | |
{ | |
ExecutionEntryPoint.ReportUnhandledException(source, eventArgs.Exception); | |
} | |
} | |
} | |
public sealed class VstoUnhandledExceptionEventArgs : EventArgs | |
{ | |
internal VstoUnhandledExceptionEventArgs(Exception exception) | |
{ | |
if (exception == null) | |
{ | |
throw new ArgumentNullException("exception"); | |
} | |
this.Exception = exception; | |
} | |
public Exception Exception { get; private set; } | |
} | |
public static class ExecutionEntryPoint | |
{ | |
public static event EventHandler<VstoUnhandledExceptionEventArgs> UnhandledException; | |
internal static void ReportUnhandledException(Type sender, Exception exception) | |
{ | |
if (sender == null) | |
{ | |
throw new ArgumentNullException("sender"); | |
} | |
if (exception == null) | |
{ | |
throw new ArgumentNullException("exception"); | |
} | |
OnUnhandledException(sender, new VstoUnhandledExceptionEventArgs(exception)); | |
} | |
private static void OnUnhandledException(object sender, VstoUnhandledExceptionEventArgs e) | |
{ | |
var handler = UnhandledException; | |
if (handler != null) | |
{ | |
handler(sender, e); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment