我发现我的 ASP.NET 3.5 Web 应用程序中的代码抛出的异常似乎由 ASP .NET 处理,与框架代码抛出的异常处理不同。让我举例说明:
这个异常:
//some code
throw new Exception("Something bad happened.");
似乎没有触发我的 global.asax 类中的 Application_Error 处理程序,并导致 asp.net 运行时错误页面出现异常消息和堆栈跟踪,尽管编译 debug="false"和 customErrors mode="On "defaultRedirect=... web.config 中的设置!而这:
//some code
//throw new Exception("Something bad happened.");
object test = null;
test.ToString();
导致响应被重定向到更正应用程序错误页面。这种行为是设计使然,还是有其他我不明白的事情在起作用?
最佳答案
这不应该发生。 throw new Exception("Something bad happened.")
以与 ((string)null).ToString()
相同的方式触发全局异常处理程序。
1) 确保您在 Global.asax.cs 中正确声明了事件处理程序
public class Global : System.Web.HttpApplication {
protected void Application_Error(object sender, EventArgs e) {
// handle exception here
}
}
2) Application_Error
未捕获从新线程或服务方法(.asmx、.svc)引发的异常
[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) 有两个糟糕的异常 StackOverflowException 和 OutOfMemoryException, 当您将它们放入代码中时,确实会以不同的方式处理它们
throw new StackOverflowException();
throw new OutOfMemoryException();
正在调用 Application_Error
处理程序,但当它们“真正”发生时,它们也会破坏域的状态,并且在这些情况下不会调用处理程序(因为它们也会关闭应用程序池) .
protected void Page_Load(object sender, EventArgs e) {
// enjoy stack overflow in a little while
this.Page_Load(sender, e);
}
关于c# - 为什么 ASP.NET 似乎以不同方式处理框架和 Web 应用程序抛出的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23105926/