首页 文章

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

提问于
浏览
5

我发现我的代码在我的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();

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

1 回答

  • 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   
      }
    }
    

    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();
    }
    

    3)有两个坏屁股异常StackOverflowException和OutOfMemoryException,当你把它们扔进代码时,确实会有不同的处理方式

    throw new StackOverflowException();    
    throw new OutOfMemoryException();
    

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

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

相关问题