Go to home page mail me! RSS Feed
FoxMetrics Web Analytics

HandleError – ASP.NET Mvc Attribute

Monday, January 09, 2012 4:47 PM

I’m not a fan of hiding error messages, as it could bite you real hard. However, there are existing functionalities that just need to be discussed such as the HandleError attribute of the ASP.NET MVC application. If you are not a fan of displaying the very common Yellow Screen of Death, then HandleError should be your new friend.

By default, I take certain steps when I’m setting up a new MVC app to prevent my users from ever seeing a single error page by implementing NLog, creating custom error pages and so on and so forth.

HandleError is an action filter and MVC has several others such as Authorize, OutputCache, RequireHttps, etc.. It simply provides a way to map exceptions to a specific template, therefore, enabling you to display your custom error pages when an exception occurs or a simple generic error view.

Once an error is detected the filter first checks the controller specific folder for an error file, i.e. if you are in Home, it will check Views/Home/Error.aspx and if not found, it will default to the shared views folder at Views/Shared/Error.aspx to locate the file.

 

    [HandleError]
    public class ListController : Controller
    {
        //
        // GET: /List/
        public ActionResult Index()
        {
            return View();
        }
    }

I usually extend the System.Web.Mvc.Controller class and override its OnException method, which provides me with a single entry point to capture and log all errors as I see fit.

        protected override void OnException(ExceptionContext filterContext)
        {
            // TODO: NLog exception here. base.OnException(filterContext);
        }

Note that overriding OnException prevents HandleError from taking control, therefore, it becomes completely useless, its almost like you can’t use both, its either clean view or log error but I want and need both.

Here is my final OnException override that gives me both clean messages to my users and also logs using NLog to disk and database for my review.

        protected override void OnException(ExceptionContext filterContext)
        {
            // TODO: NLog exception here.

            // Handle exception
            if (filterContext.HttpContext.IsCustomErrorEnabled)
            {
                filterContext.ExceptionHandled = true;
                Response.StatusCode = 500;
                Response.TrySkipIisCustomErrors = true;
                this.View("Error").ExecuteResult(this.ControllerContext);

                //
                base.OnException(filterContext);
            }
        }

Your Comments.

No comments posted yet.

Your Reply.

Comment Form.

Fields denoted with a "*" are required.

You may also like to leave your email or website.

 
Please add 2 and 6 and type the answer here:

Preview Your Comment.

 
Next entries »