How to get ELMAH to work with ASP.NET MVC [HandleError] attribute?

前端 未结 8 2071
后悔当初
后悔当初 2020-11-22 02:53

I am trying to use ELMAH to log errors in my ASP.NET MVC application, however when I use the [HandleError] attribute on my controllers ELMAH doesn\'t log any errors when the

8条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 03:03

    This is exactly what I needed for my MVC site configuration!

    I added a little modification to the OnException method to handle multiple HandleErrorAttribute instances, as suggested by Atif Aziz:

    bear in mind that you may have to take care that if multiple HandleErrorAttribute instances are in effect then duplicate logging does not occur.

    I simply check context.ExceptionHandled before invoking the base class, just to know if someone else handled the exception before current handler.
    It works for me and I post the code in case someone else needs it and to ask if anyone knows if I overlooked anything.

    Hope it is useful:

    public override void OnException(ExceptionContext context)
    {
        bool exceptionHandledByPreviousHandler = context.ExceptionHandled;
    
        base.OnException(context);
    
        Exception e = context.Exception;
        if (exceptionHandledByPreviousHandler
            || !context.ExceptionHandled  // if unhandled, will be logged anyhow
            || RaiseErrorSignal(e)        // prefer signaling, if possible
            || IsFiltered(context))       // filtered?
            return;
    
        LogException(e);
    }
    

提交回复
热议问题