在异常日志记录中抛出异常

Exception thrown inside Exceptional logging

我正在用 Exceptional 替换 Elmah,但遇到了问题。如果在我的 Web 项目中抛出异常或者错误是 404(找不到路径“/blah/blah”的控制器或未实现 IController),它工作正常。

但是,如果我从我引用的项目之一中抛出异常,而该项目不是我的 Web 项目,那么 Exceptional 在尝试记录时会抛出错误。以下错误和堆栈跟踪仅显示在控制台中。错误在那个时候被吞没了,没有被记录在任何地方。

开源的优点之一是,我可以看到抛出异常的代码,但不知道为什么...

Error.cs (line 107, 135, 126)

Exception thrown: 'System.ArgumentException' in Cms.Services.dll
'w3wp.exe' (CLR v4.0.30319: /LM/W3SVC/1/ROOT/wssp-18-131152201224510365): Loaded 'C:\Windows\assembly\GAC_MSIL\Microsoft.VisualStudio.Debugger.Runtime.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.Debugger.Runtime.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
System.NullReferenceException: Object reference not set to an instance of an object.
   at System.Web.HttpRequest.CalcDynamicServerVariable(DynamicServerVariable var)
   at System.Web.HttpServerVarsCollectionEntry.GetValue(HttpRequest request)
   at System.Web.HttpServerVarsCollection.GetServerVar(Object e)
   at System.Web.HttpServerVarsCollection.Get(Int32 index)
   at System.Web.HttpServerVarsCollection.GetValues(Int32 index)
   at System.Collections.Specialized.NameValueCollection.Add(NameValueCollection c)
   at StackExchange.Exceptional.Error.<>c__DisplayClass22_0.<SetContextProperties>b__0(Func`2 getter) in C:\BuildAgent\work\d20fce4a5bb47bd3\StackExchange.Exceptional\Error.cs:line 126
   at StackExchange.Exceptional.Error.SetContextProperties(HttpContext context) in C:\BuildAgent\work\d20fce4a5bb47bd3\StackExchange.Exceptional\Error.cs:line 135
   at StackExchange.Exceptional.Error..ctor(Exception e, HttpContext context, String applicationName) in C:\BuildAgent\work\d20fce4a5bb47bd3\StackExchange.Exceptional\Error.cs:line 107
   at StackExchange.Exceptional.ErrorStore.LogException(Exception ex, HttpContext context, Boolean appendFullStackTrace, Boolean rollupPerServer, Dictionary`2 customData, String applicationName) in C:\BuildAgent\work\d20fce4a5bb47bd3\StackExchange.Exceptional\ErrorStore.cs:line 611

我正在像这样注册 Exceptional:

  string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyApp"].ConnectionString;
  ErrorStore.Setup("MyApp", new SQLErrorStore(connectionString));

这是我的唯一代码 web.config:

<modules runAllManagedModulesForAllRequests="true">
  <add name="ErrorStore" type="StackExchange.Exceptional.ExceptionalModule, StackExchange.Exceptional" />
</modules>

我终于找到问题了。下面的代码是我用来从我的应用程序中注销用户的代码。

var authenticationManager = HttpContext.GetOwinContext().Authentication;
authenticationManager.SignOut();
authenticationManager.User = new ClaimsPrincipal();

当第 3 行执行并将用户设置为新的 ClaimsPrinciple 时,它会删除以下 3 个值(AUTH_TYPE、AUTH_USER、REMOTE_USER)并设置它们在 System.Web.HttpContext.Current.Request.ServerVariables 对象内为 null,即使键仍在对象内。

因此 Stackexchange.Exceptional 不会记录该行之后抛出的任何异常,因为它会尝试读取这些值,然后抛出 System.NullReferenceException.