如何忽略全局 asax 中映像的日志记录错误



我的global.asax中有一个错误处理程序,如下所示;

  Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
        ' Code that runs when an unhandled error occurs
        Dim ex = Server.GetLastError.GetBaseException
        Dim lastErrorWrapper As HttpException = Server.GetLastError()
        Dim lastError As Exception = lastErrorWrapper
        If lastErrorWrapper.InnerException IsNot Nothing Then
            lastError = lastErrorWrapper.InnerException
        End If
        My.ErrorHandler.LogError( _
            "<BR/><BR/>URL: " & Request.RawUrl & _
            "<BR/><BR/>STACK: " & ex.StackTrace & _
            "<BR/><BR/>SOURCE: " & ex.Source & _
            "<BR/><BR/>MESSAGE: " & ex.Message & _
            "<BR/><BR/>TYPENAME: " & ex.GetType.ToString & _
            "<BR/><BR/>INNER EXCEPTION: " & lastError.ToString & _
            "<BR/><BR/>REFERRER: " & HttpContext.Current.Request.Url.AbsoluteUri & _
            "<BR/><BR/>USER IP: " & Request.ServerVariables("REMOTE_ADDR") & " -- " & Request.ServerVariables("HTTP_USER_AGENT"))
    End Sub

显然,这很好用,每当出现错误时都会给我发送电子邮件。但是,对于文件系统中找不到的任何映像也是如此。它给了我一个"文件不存在"错误。有没有办法忽略不在磁盘上的映像的日志记录错误?

你不能解决FileNotFoundException吗?如果不应发生异常,则宁愿解决问题而不是抑制它。若要处理已知异常,可以使用以下代码。

if(Server.GetLastError().GetBaseException() is System.Web.HttpException)
{
     //You could check whether the 
     //Server.GetLastError().GetBaseException().Message contains the appropriate message
     Debug.WriteLine("Suppressed FileNotFoundException");
}else
//Log an unhandled exception
var ex = Context.Error;
if (ex is HttpException)
{
    var httpException = (HttpException)ex;
    if (httpException.GetHttpCode() == (int)HttpStatusCode.NotFound)
        return; // Do nothing 404    
}
我知道

这听起来很容易,或者非常简单,或者您可以搜索错误代码,但这就是我所做的 - 简单检查错误是否包含dose not exist消息:

lastErrorWrapper.ToString().Contains("does not exist.")

最新更新