4

可能重复:
elmah:没有 HttpContext 的异常?

Global.asax

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
        throw new Exception("TEST");
    }


    // ... other usual methods
}

Elmah没有记录异常。

我在这里做了很多初始化和配置工作,如果出现任何问题,我得到错误日志是很重要的。

不知道为什么它不起作用,但可能与 MVC 生命周期有关 - 也许HttpContext现阶段没有?有没有办法通过Elmah这里记录错误?

4

1 回答 1

1

你对一件事绝对是正确的,HttpContext.Current不存在于 中Application_Start,这可能是 Elmah 不从该方法记录错误的问题之一。

但是,如果您在 Application_Start 中出现异常,那么与 Elmah 没有记录异常相比,您遇到的问题更大。您的Application_Start方法应该是完美的,或者如果不是,则需要编写它以便它在您的开发环境中失败,以便您可以在将其推送到生产之前看到问题。如果是间歇性异常,我建议将问题代码放在其他地方。

更新

根据您的评论,也许这对您有用。它还具有检查每个请求以查看它是否第一次失败的额外好处。

protected void Application_BeginRequest(object sender, EventArgs args)
{
  CheckConfiguration();
}

private static readonly object ConfigurationLockObject = new object();
private void CheckConfiguration()
{
  /** Lock Bypass **/
  if (IsConfigured()) 
  {
    return;
  }

  // The lock ensures the configuration only gets called one at a time.
  lock (ConfigurationLockObject)
  {
    // Must check for configuration again, just in case multiple threads had hit the lock
    if (!IsConfigured())
    {
      try
      {
        // Configuration Code
      }
      catch (Exception exception)
      {
        Log.Error("Exception Occurred", exception);
      }
    }
  }
}
于 2011-07-13T15:02:38.437 回答