How to get exception information in shared error.cshtml

I am using ASPNet MVC4 with a HandleErrorAttribute filter configured on Global.asax

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

On my web.config, I configured customError mode for RemoteOnly:

 <customErrors mode="RemoteOnly" /> 

So, the user is redirected to ~ / Shared / Error.cshtml, when an exception is thrown on any view, this is normal.

Now I can catch this exception for the log:

~ / General / Error.cshtml code:

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

This code actually works fine (without the EX parameter), but I need to improve my log, including exception information.

How can I get exception information on this page?

+6
source share
2 answers

I would recommend writing a custom handler and entering it, for example.

 [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", ex); } } 
+7
source

Just make your Error.cshtml view strictly printed on HandleErrorInfo , which is the model passed to this view using HandleErrorAttribute:

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

And by the way, registering inside the view does not seem to be the cleanest thing you could do. I would rather write my own error handler attribute and register an exception there.

+10
source

All Articles