Asp.net

如何獲取有關共享 error.cshtml 的異常詳細資訊

  • November 8, 2018

我正在使用帶有在 Global.asax 上配置的 HandleErrorAttribute 過濾器的 ASPNet MVC4

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
   filters.Add(new HandleErrorAttribute());
}

在我的 web.config 上,我已將 customError 模式配置為 RemoteOnly:

<customErrors mode="RemoteOnly" />

因此,當任何視圖引發異常時,使用者將被重定向到 ~/Shared/Error.cshtml,這沒關係。

現在,我可以為日誌擷取此異常:

~/Shared/Error.cshtml 程式碼:

@{
   log4net.LogManager
     .GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
     .Fatal("Not captured exception", ex);
}

實際上這段程式碼工作正常(沒有 EX 參數),但我需要改進我的日誌,包括異常詳細資訊。

如何在此頁面上獲取異常詳細資訊?

我建議編寫一個自定義處理程序並在其中登錄,例如

[AttributeUsage(AttributeTargets.All, Inherited = true)]
public class HandleErrorAttributeCustom : HandleErrorAttribute
{

   public override void OnException(ExceptionContext context)
   {
               base.OnException(context);
          log4net.LogManager
         .GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
         .Fatal("Not captured exception", context.Exception);
   }
}

只需使您的Error.cshtml視圖強類型化,HandleErrorInfoHandleErrorAttribute 將模型傳遞給該視圖:

@model System.Web.Mvc.HandleErrorInfo
@{
   log4net
       .LogManager
       .GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
       .Fatal("Not captured exception", Model.Exception);
}

順便說一句,在視圖中登錄似乎不是你能做的最乾淨的事情。我寧願編寫我的自定義錯誤處理程序屬性並在那裡記錄異常。

引用自:https://stackoverflow.com/questions/22100171