James
James

Reputation: 7543

ASP.NET error handling - not detecting the right error type in Global.asax

I have some custom error classes defined, each with their own functionality (not shown):

Exceptions.cs

public abstract class MyAppException : Exception {
  //...
}
public class ValidationException : MyAppException {
  //...
}
public class AccessDeniedException : MyAppException {
  //...
}

Now in the codebehind of a blank page I have:

test.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
  throw new AccessDeniedException();
}

My intention is to catch this at the application level:

Global.asax.cs

protected void Application_Error(object sender, EventArgs e) {
  var exc = Server.GetLastError();
  if (exc is MyAppException) ((MyAppException)exc).Log();
}

But by adding a breakpoint I find that exc is MyAppException evaluates as false.

Where am I going wrong?

Upvotes: 1

Views: 128

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039398

Try the InnerException:

if (exc.InnerException is MyAppException)

It's the System.Web.UI.Page.HandleError method that wraps the actual exception into an HttpUnhandledException.

Upvotes: 2

Related Questions