2

I have default template of MVC4 project and following subscription for UnhandledException event in my Global.asax:

    [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlAppDomain)]
    protected void Application_Start()
    {
        AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
    }

    void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        Debugger.Break();
        // Some logging code here
    }

In my HomeController Index action I simply write:

    throw new Exception("Test exception"):

Console application with such subscription works fine. But in MVC project handler call never occurs. What is wrong with MVC?

  • possible duplicate of [Error Handling in ASP.NET MVC](http://stackoverflow.com/questions/812235/error-handling-in-asp-net-mvc) – Levi Dec 24 '13 at 15:56
  • There is a good explanation here http://stackoverflow.com/a/16348903/441729 as to why AppDomain.CurrentDomain.UnhandledException doesn't work for an app pool running in IIS. – grahamesd May 16 '17 at 19:53

1 Answers1

0

UnhandledException callback is not called because when action raise exception its handled by MVC framework and AppDomain doesn't have unhandled exception so its not candidate to be unloaded and it can handle next request.

The shortest way to log exception:

protected void Application_Error(object sender, EventArgs args)
{
    Debugger.Break();
    Exception error = ((HttpApplication)sender).Context.Server.GetLastError();
    // Some logging code here
}
Sergii
  • 44
  • 2
  • 5