Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get exception details on shared error.cshtml

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

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

On my web.config I have configured customError mode to RemoteOnly:

<customErrors mode="RemoteOnly" />

So, the user are redirected to ~/Shared/Error.cshtml when a exception are raised on any View, that`s ok.

Now, I can catch this exception for log:

~/Shared/Error.cshtml code:

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

Actually this code are working fine (without EX parameter), but I need to improve my log including exception details.

How I can get exception details on this page?

like image 780
rkawano Avatar asked Feb 28 '14 16:02

rkawano


2 Answers

Just make your Error.cshtml view strongly typed to HandleErrorInfo which is the model being passed to this view by the HandleErrorAttribute:

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

And by the way, logging inside a view doesn't seem like the cleanest thing you could do. I'd rather write my custom error handler attribute and log the exception there.

like image 63
Darin Dimitrov Avatar answered Nov 07 '22 06:11

Darin Dimitrov


I'd recommend writing a custom handler and log within, e.g.

[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);
    }
}
like image 34
dove Avatar answered Nov 07 '22 07:11

dove