OnException method is never ran

156 views Asked by At

I am building an ASP.NET MVC 5 web app. Using the following, my OnException method is never ran (I can't break point it and throwing an uncaught exception doesn't do anything either so I am assuming it is never run)

using Elmah;
using System;
using System.Web;
using System.Web.Mvc;

namespace App.WebUI
{
    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new ElmahHandledErrorLoggerFilter());
            filters.Add(new HandleErrorAttribute());
        }
    }

    public class ElmahHandledErrorLoggerFilter : IExceptionFilter
    {
        public void OnException(ExceptionContext context)
        {
            // Log only handled exceptions, because all other will be caught by ELMAH anyway.
            if (context.ExceptionHandled)
            {
                ErrorSignal.FromCurrentContext().Raise(context.Exception);
            }
        }
    }
}

Here is my global.asx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace App.WebUI
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}

Please help.

1

There are 1 answers

1
malkam On

Try this:

Make sure you've enabled custom errors in root web.config.

<system.web>
<customErrors defaultRedirect="~/Error"
                    mode="On">

      </customErrors>
</system.web>

After doing this I've verified in my local ElmahHandledErrorLoggerFilter.OnException executed.

I've explicitly throwing exception from controller to test functionality.

Below is my code:

TestController:

public ActionResult Index()
        {
            throw new Exception("gone!");
} 

FilterConfig.cs

public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new ElmahHandledErrorLoggerFilter());
            filters.Add(new HandleErrorAttribute());
        }
        public class ElmahHandledErrorLoggerFilter : IExceptionFilter
        {
            public void OnException(ExceptionContext context)
            {
                // Log only handled exceptions, because all other will be caught by ELMAH anyway.
                //it is true
                if (context.ExceptionHandled)
                {
                    var dsf=context.ExceptionHandled;
                }
            }
        }
    }

It may solve your problem