webapi and unhandled exception hook per appdomain

2019-05-30 17:22发布

问题:

Having a WebApi 2.2 application - is it possible to make use of AppDomain's UnhandledException hook?

I have a code similar to this:

[assembly: OwinStartup("DevConfiguration", typeof(DevStartup))]
namespace WebApi.Module
{
  public class DevStartup
  {
     private const string ErrorEventSourceName = "WebApiHost";
     private const int ErrorEventId = 600;

     [SecurityPermission(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlAppDomain)]
     public void Configuration(IAppBuilder app)
      {

         AppDomain.CurrentDomain.UnhandledException += AppDomain_UnhandledException;
          ...
          throw new Exception("some exception);
       }
    public static void AppDomain_UnhandledException(Object sender, UnhandledExceptionEventArgs e)
    {
        EventLog.WriteEntry(ErrorEventSourceName, ex.ToString(),EventLogEntryType.Error, ErrorEventId);
    }
   }
}

The UnhandeledException hook is never called... What is the reason - how to make this work and catch all the uncaught exceptions (beside a global exception handler - which would handle exceptions on request contexts).