为什么ASP.NET看似处理框架和Web应用程序抛出的异常会有所不同?

use*_*689 5 .net c# asp.net exception

我发现我的代码在我的ASP.NET 3.5 Web应用程序中抛出的异常似乎由ASP .NET处理的不同于框架代码抛出的异常.让我说明一下:

这个例外:

//some code   
throw new Exception("Something bad happened.");
Run Code Online (Sandbox Code Playgroud)

似乎没有触发我的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();
Run Code Online (Sandbox Code Playgroud)

导致响应被重定向到正确的应用程序错误页面.这种行为是设计的,还是在这里有其他一些我不理解的事情?

Ond*_*dar 2

这不应该发生。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   
  }
}
Run Code Online (Sandbox Code Playgroud)

2) 从新线程或服务方法(.asmx、.svc)引发的异常未被捕获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();
}
Run Code Online (Sandbox Code Playgroud)

3)有两个糟糕的异常 StackOverflowException 和 OutOfMemoryException,当您将它们扔到类似的代码中时,它们的处理方式确实不同

throw new StackOverflowException();    
throw new OutOfMemoryException();
Run Code Online (Sandbox Code Playgroud)

正在调用处理程序Application_Error,但是当它们“真正”发生时,它们也会破坏域的状态,并且在这些情况下不会调用处理程序(因为它们也关闭了应用程序池)。

protected void Page_Load(object sender, EventArgs e) {
  // enjoy stack overflow in a little while
  this.Page_Load(sender, e);
}
Run Code Online (Sandbox Code Playgroud)