I've found out that exceptions thrown by my code in my ASP.NET 3.5 web application, seem to be handled differently by ASP .NET than those thrown by the framework code. Let me illustrate:
this exception:
//some code
throw new Exception("Something bad happened.");
doesn't seem to trigger the Application_Error handler in my global.asax class and results in a asp.net runtime error page with the exception message and stack trace, despite the compilation debug="false" and customErrors mode="On" defaultRedirect=... settings in web.config! Whereas this:
//some code
//throw new Exception("Something bad happened.");
object test = null;
test.ToString();
results in the response being redirected to correct application error page. Is this behavior something by design, or are there some other things at play here that I don't understand?
This shouldn't happen. throw new Exception("Something bad happened.")
is firing the global exception handler the same way ((string)null).ToString()
does.
1) Make sure you have you're event handler in Global.asax.cs declared correctly
public class Global : System.Web.HttpApplication {
protected void Application_Error(object sender, EventArgs e) {
// handle exception here
}
}
2) The exceptions being fired from new thread or from service methods (.asmx, .svc) are not being caught by Application_Error
[ServiceContract]
public interface IService {
[OperationContract]
void DoWork();
}
public class Service : IService {
public void DoWork() {
throw new Exception("No Application_Error for me, please.");
}
}
protected void Page_Load(object sender, EventArgs e) {
new Thread(() => {
throw new Exception("No Application_Error for me, either.");
}).Start();
}
3) there are two bad-ass exceptions StackOverflowException and OutOfMemoryException, those indeed are handled differently when you throw them in code like
throw new StackOverflowException();
throw new OutOfMemoryException();
the Application_Error
handler is being called, but when they occur "for real" they also corrupt state of domain and handler is not being called in those cases (because they shut down application pool as well).
protected void Page_Load(object sender, EventArgs e) {
// enjoy stack overflow in a little while
this.Page_Load(sender, e);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With