【问题标题】:Where or when to log exceptions in an MVC 5 application在 MVC 5 应用程序中何时何地记录异常
【发布时间】:2016-09-12 17:01:50
【问题描述】:

我想听从很多建议,只使用全局HandleErrorAttribute,但这个属性似乎直接显示Error 视图,让我没有地方记录异常。我不认为视图是记录日志和其他业务逻辑的正确位置。

我还可以选择在我的BaseController 中覆盖OnException,但我担心与HandleErrorAttribute 发生冲突。如果我按如下方式覆盖OnException,不处理异常,它会继续到HandleErrorAttribute吗?

protected override void OnException(ExceptionContext filterContext)
{
    Exception exception = filterContext.Exception;
    var controller = filterContext.RouteData.Values["controller"].ToString();
    var action = filterContext.RouteData.Values["action"].ToString();
    logger.Error(exception, "Exception in controller '{0}': action '{1}'.", controller, action);
    filterContext.Exception = exception;
    //filterContext.ExceptionHandled = true;
}

或者我该如何记录异常?我相信上述两种方法使我免于在每个操作方法上实现“try-catch”,并且捕获特定异常可能会很麻烦。我还希望可以选择重新启动应用程序,或者如果发生真正灾难性的异常,再次HandleErrorAttribute 并没有留下太多空间。

【问题讨论】:

    标签: c# asp.net-mvc logging exception-handling asp.net-mvc-5


    【解决方案1】:

    通常,Global.asax 是这样做的好地方:

    protected void Application_Error(object sender, EventArgs e)
    {
        // Get the exception object.
        Exception exception = Server.GetLastError();
    
        // Handle Exception
    
        // Call Server.ClearError() if the exception is properly handled
    }
    

    【讨论】:

    【解决方案2】:

    查看 StackExchange.Exceptional,它是为 SO 创建和使用的开源异常记录器。

    https://github.com/NickCraver/StackExchange.Exceptional

    【讨论】:

      【解决方案3】:

      是的,使用 Global.asax

      protected void Application_Error(object sender, EventArgs e)
      {
         System.Web.HttpRuntime.UnloadAppDomain();
      }
      

      【讨论】:

      • 关闭应用程序只是一个例外情况。我的问题的重点是关于在哪里进行异常日志记录。不过谢谢,我不知道如何关机。
      猜你喜欢
      • 2017-06-06
      • 1970-01-01
      • 1970-01-01
      • 2010-11-03
      • 2010-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多