Justin
Justin

Reputation: 31

ASP.NET Global.asax Application_Error works but not when using the Error event

I have an ASP.NET MVC application that is supposed to catch all unhandled exceptions within the global.asax application error handler.

If I define the handler as follows:

protected void Application_Error(object sender, EventArgs e)

then it works fine. However, if within the Application_Start event I try and do:

this.Error += new EventHandler(Application_Error);

The actual event is never called.

Does anyone know why and if so what i'm doing incorrectly?

Upvotes: 3

Views: 1597

Answers (2)

TheMule
TheMule

Reputation: 21

The event is not being called either because Exceptions are being caught somewhere else in the application (and swallowed maybe) or because you are registering the event in the Application_Start event (not needed). You want to do something like this in your Application_Error:

protected void Application_Error(object sender, EventArgs e) {
  Exception exception = Server.GetLastError();
  // log exception
  // Email exception
}

I use this method to both log and E-mail uncaught errors for all my applications. Hope this helps.

Upvotes: 0

Paul
Paul

Reputation: 36349

You shouldn't have to add to the error event explicitly; Application_Error should get called automatically by the framework.

Upvotes: 3

Related Questions