如何在global.asax之外捕获应用程序错误?

时间:2011-09-15 16:59:44

标签: c# asp.net

如何在global.asax之外捕获应用程序错误?我想在global.asax

之外捕获未处理的异常

2 个答案:

答案 0 :(得分:1)

每个页面都来自System.Web.UI.Page。您可以覆盖每个单独页面的OnError方法,如下所示:

protected override void OnError(EventArgs e)
{
    // Capture the exception.
    var exception = HttpContext.Current.Server.GetLastError();

    // Create an error message.
    var errorInfo = 
       "<br/>URL: " + HttpContext.Current.Request.Url.ToString() +
       "<br/>Source: " + exception.Source + 
       "<br/>Message: " + exception.Message +
       "<br/>Stack trace: " + exception.StackTrace;

    // Write out the error message. You can do whatever you want with it.
    HttpContext.Current.Response.Write(errorInfo);

    // Clear the error that you handled from the cache so it's not read again.
    HttpContext.Current.Server.ClearError();

    // Perform the normal operations that would happen if you didn't override.
    base.OnError(e);
}

答案 1 :(得分:0)

是的,页面上有几个地方,包括page_error 查看: http://msdn.microsoft.com/en-us/library/aa479319.aspx

另请查看elmah的错误记录

http://code.google.com/p/elmah/