在global.asax中捕获特定错误

本文关键字:错误 global asax | 更新日期: 2023-09-27 18:01:42

我在全局asax中使用Application_Error事件来捕获错误并将它们写入文件。我可以在网页中看到特定的异常,但在日志文件中,我所看到的是一个像这样的通用错误:

Exception of type 'System.Web.HttpUnhandledException' was thrown.
   at System.Web.UI.Page.HandleError(Exception e)
   at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
   at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
   at System.Web.UI.Page.ProcessRequest()
   at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context)
   at System.Web.UI.Page.ProcessRequest(HttpContext context)
   at ASP.review_aspx.ProcessRequest(HttpContext context) in c:'Windows'Microsoft.NET'Framework'v2.0.50727'Temporary ASP.NET Files'...'ff7eee7c'ff24ade1'App_Web_tddyd4bt.3.cs:line 0
   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

我怎么能写的错误,我在黄页看到的日志文件,而不是这个通用的错误?

在global.asax中捕获特定错误

这是你想要的吗?

 Exception ex = Server.GetLastError();    
 String ExceptionMessage = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message;

在全局。asax,找到Application_Error方法并添加以下内容:

 protected void Application_Error(object sender, EventArgs e)
    {
       Exception ex = Server.GetLastError();
        LogHelper.WriteLog(ex);
    }

你需要创建一个类来写日志。

public class LogHelper
{
    public static void WriteLog(Exception exception)
    {
       //write to text file the exception.Message ...
    }
}