捕获 C# 中的所有异常 ASP.NET 而不是“try{} catch{}”块中的每个方法

本文关键字:catch try 方法 异常 ASP 捕获 NET | 更新日期: 2023-09-27 18:33:43

有没有更好的方法在一个地方捕获所有异常,而无需为每个方法编写try{} catch{}

捕获 C# 中的所有异常 ASP.NET 而不是“try{} catch{}”块中的每个方法

您可以通过

覆盖在 Global.asax 中找到Application_Error来捕获应用程序中的异常。但是,使用此方法,您无法像使用常规try catch块那样对这些异常执行操作。

您可以记录它

void Application_Error(object sender, EventArgs e)
{
     Exception ex = Server.GetLastError();
     // if there's an Inner Exception we'll most likely be more interested in that
     if (ex .InnerException != null)
     {
         ex = ex .InnerException;
     }
     // filter exception using ex.GetType() ...
     // log exception ...
     // Clear all errors for the current HTTP request.
     HttpContext.Current.ClearError();
}

和/或重定向

void Application_Error(object sender, EventArgs e)
{
     Exception ex = Server.GetLastError();
     // process exception
     // redirect
     HttpContext.Current.ClearError();             
     Response.Redirect("~/Error.aspx", false);
     return;
}

这是你所能做的。

谢谢大家。我从一个网站上得到了答案。这是我根据异常修改的代码,并在应用程序中使用第三方(Elmah)记录错误。希望,这对其他人有帮助。

void Application_Error(object sender, EventArgs e) 
{ 
    // Code that runs when an unhandled error occurs
    //Get the exception object
    Exception exceptionObject = Server.GetLastError();
    try
    {
      if (exceptionObject != null)
      {
         if (exceptionObject.InnerException != null)
         {
            exceptionObject = exceptionObject.InnerException;
         }
         switch (exceptionObject.GetType().ToString())
         {
            case "System.Threading.ThreadAbortException":
                HttpContext.Current.Server.ClearError();
                break;
            default:
                // log exception ...
                //Custom method to log error
                Elmah.ErrorSignal.FromCurrentContext().Raise(exceptionObject);
                break;
            }
        }
    }
    catch 
    {
        //Avoiding further exception from exception handling
    }
}