ma.citi

A Coder's Blog

MVC 5 How to Handle Controller-Level Errors

Catching and handling errors at controller level can be very useful. Sometimes we don’t want to handle some errors at application level How to: Handle Application-Level Errors.

There are different ways to handle controller-level errors in MVC. Each one of them with its own pro and cons.

For example you can use an exception filter or you can override the OnException method of the controller class. I’m going to show the latter.

I just created a new controller named “TestController”, and a new View named “Error” under the View > Test folder.

    public class TestController : Controller
    {
        public ActionResult Index()
        { 
           throw new NotImplementedException();
        }

        protected override void OnException(ExceptionContext exceptionContext)
        {
            //retrieve the exception
            Exception ex = exceptionContext.Exception;
            exceptionContext.ExceptionHandled = true;

            //retrieve other info
            var controllerName = exceptionContext.RouteData.Values["controller"] as string;
            var actionName = exceptionContext.RouteData.Values["action"] as string;
            var errorInfo = new HandleErrorInfo(exceptionContext.Exception, controllerName, actionName);

            //DO SOME LOGGING

            //redirect to error view
            exceptionContext.Result = new ViewResult { ViewName = "Error" };
        }
    }

The exception thrown in the action Index will be caught by the OnExection method. In the exceptionContext object you will have all the info you need for logging the error for example.

You could also return specific views based on the type of the exception caught. For example a “NotFound” view if a custom ProductNotFoundException is thrown by the action Details(string sku) of the ProductController.

NOTE: You can’t handle controller-level errors in this way using .NET core. There isn’t a OnException method in the controller class anymore.