user247702
user247702

Reputation: 24212

Application_Error - GetLastError() or GetLastError().GetBaseException()

When handling an error in Application_Error, which of those two should I use?

I'm finding multiple examples for both, but it's not really clear if one is better than the other. Are there cases where only one will show the correct error?

Also, I doubt this matters, but the application is using MVC 4.

Upvotes: 7

Views: 1472

Answers (1)

default locale
default locale

Reputation: 13446

It depends on what exactly do you need.

From the documenation of Exception.GetBaseException:

When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions.

Application_Error handles exceptions on the upper level, maybe after several exception handling mechanisms, so if exception is thrown like this:

try {
   //Lots of code, method calls, etc...
   try {
       throw new FooException("Foo");
   } catch(FooException fe) {
       throw new BarException("Bar", fe);
   }
}catch(BarException be) {
    throw new FooBarException("FooBar", be);
}

then GetLastError will get you FooBarException, while GetLastError().GetBaseException() will get you FooException. So the former returns actual unhandled exception while the latter returns the root cause.

I assume that Foo, Bar and FooBar exception classes do not override GetLastError or InnerException

Upvotes: 7

Related Questions