asp.net-mvcerror-handlingwebactivator

Capturing ASP.NET MVC Errors and WebActivator


I want to know if it's possible to capture unhandled errors without modifying the web.config or global.asax files.

Ideally I would use the WebActivator package and have something like this:

[assembly: WebActivator.PostApplicationStartMethod(typeof(MyProject.Initialize), "Start")]

namespace MyProject
{
    using System;
    using System.Collections.Generic;
    using System.Web;
    using System.Web.Mvc;

    internal static Initialize
    {
        public static void Start()
        {
              // this doesn't work
              HttpContext.Current.ApplicationInstance.Error += ApplicationInstance_Error;
        }

        // this never fires
        static void ApplicationInstance_Error(object sender, EventArgs e)
        {
            throw new NotImplementedException();
        }
    }
}

Question #1: Is it possible to capture unhandled errors without modifying the web.config or global.asax files?

Question #2: How?

Update: I posted an answer below. I'm not sure if this is the best way to do it. Any comments appreciated.


Solution

  • I was able to get something working using this method:

    [assembly: WebActivator.PreApplicationStartMethod(typeof(MyProject.Initialize), "Start")]
    
    namespace MyProject
    {
        using System;
        using System.Collections.Generic;
        using System.Web;
        using System.Web.Mvc;
    
        internal static Initialize
        {
            public static void Start()
            {
                GlobalFilters.Filters.Add(new WatchExceptionAttribute());
            }
        }
    
        public class CustomHandleErrorAttribute : HandleErrorAttribute
        {
            public override void OnException(ExceptionContext filterContext)
            {
                // do your thing here.
            }
        }
    }