用NLog和Try Catch处理错误

本文关键字:处理 错误 Catch Try NLog | 更新日期: 2023-09-27 18:25:48

我使用NLog在操作中记录错误,以存储带有附加信息的错误,例如:

using NLog;
private static Logger _logger = LogManager.GetCurrentClassLogger();
public virtual ActionResult Edit(Client client)
{
  try
  {
        // FORCE ERROR
        var x = 0;
        x /= x;
        return RedirectToAction(MVC.Client.Index());
  }
  catch (Exception e)
  {
    _logger.Error("[Error in ClientController.Edit - id: " + client.Id + " - Error: " + e.Message + "]");
  }
}

我在Web.config中配置了错误处理:

<customErrors mode="On" />

但当我执行Action时,我不会被重定向到Error.cshtml(页面保持在同一位置),为什么?

我可以用Elmah做同样的事情吗?(记录客户端Id等附加信息)

用NLog和Try Catch处理错误

首先,大多数人通过而不是捕获异常来解决此错误。这样,异常会传播到ASP.NET,ASP.NET会显示一个"500内部错误"网页,所有相关信息都会被记录下来。

  • 如果您的服务器配置为生产,错误页面只会显示"发生错误,记录了详细信息。"

  • 如果服务器被配置为用于开发,那么您将获得著名的黄页,其中包含异常类型、消息和堆栈跟踪。

吞下异常并手动重定向到错误页面是一种糟糕的做法,因为它会隐藏错误。有一些工具可以检查日志,并为您提供很好的统计数据,例如成功/失败请求的百分比,但这些工具已经不起作用了。

所以,不接受例外是人们所做的,至少,它解决了你的问题。


现在,我觉得这很笨拙,因为我不喜欢手动查找黄页中提到的源文件,并手动转到提到的行号。我实际上对黄页没有用,它还不如说"发生了一个错误,哭得我像条河,不,不,"我不读黄页。

相反,我确实喜欢自己记录异常,我让我的记录器以full-path-to-source-filename(line):开始每一行,这样visualstudio中调试日志上的每一行都可以点击,点击一行会自动打开正确的源文件,并滚动到发出日志消息的确切行。如果你想要这种奢侈,那么就继续捕获异常,但在记录异常后,你必须重新思考它,这样事情才能正常进行。

修正

以下是评论中添加的一些信息:

因此,您可以执行以下操作:

try
{
   ...
}
catch (Exception e)
{
    log( "information" );
    throw; //special syntax which preserves original stack trace
}

try
{
   ...
}
catch (Exception e)
{
    throw new Exception( "information", e ); //also preserves original stack trace
}

执行而不是执行此操作:catch( Exception e ) { log( "information" ); throw e; },因为它丢失了e的原始堆栈跟踪信息。

在您的代码中,错误发生在除法部分(x/=x),因此没有执行重定向行(索引页)catch部分中定义重定向到Error.cshtml。

注意:当您使用try-catch块时,ASP.NET级别不会发生错误,因此不会重定向到error.cshtml页面

using NLog;
private static Logger _logger = LogManager.GetCurrentClassLogger();
public virtual ActionResult Edit(Client client)
{
  try
  {
        // FORCE ERROR
        var x = 0;
        x /= x; /// error occur here
        return RedirectToAction(MVC.Client.Index()); /// no execution of this line
  }
  catch (Exception e)
  {
    _logger.Error("[Error in ClientController.Edit - id: " + client.Id + " - Error: " + e.Message + "]");
    /// add redirect link here 
     return RedirectToAction(MVC.Client.Error()); /// this is needed since the catch block execute mean no error at ASP.net level resulting no redirect to default error page
  }
}

这将简化异常处理,并使您能够更简洁地管理流程。创建这样的属性:

 public class HandleExceptionAttribute : System.Web.Mvc.HandleErrorAttribute
    {
        // Pass in necessary data, etc
        private string _data;
        public string Data
        {
            get { return _data; }
            set { _data = value; }
        }
        public override void OnException(System.Web.Mvc.ExceptionContext filterContext)
        {            
            // Logging code here
            // Do something with the passed-in properties (Data in this code)
            // Use the filterContext to retrieve all sorts of info about the request
            // Direct the user
            base.OnException(filterContext);
        }
    }

现在,您可以在控制器或方法级别上使用它,其属性如下:

[HandleException(Data="SomeValue", View="Error")]

或者,像这样在全球(global.asax)注册:

GlobalFilters.Filters.Add(new HandleExceptionAttribute());