Exception Handling in MVC

In this blog, we will see Exception handling in MVC.
There are more than one ways to handle an exception in ASP.Net MVC. Let’s see in details below –

How to Handle Exception in ASP.Net MVC?

As already mentioned above that, we can handle an exception in ASP.Net MVC in multiple ways.
We will see all the methods of handling an exception one by one.

1. Try Catch Block

It is the simplest and basic way to handle an exception. We all are aware of this process as it is a very common approach.

Sample code to handle an exception using a try-catch block.

public ActionResult DisplayProductName()
        {
            try
            {
                var product = new Products { ProductName = “Product1” };
                List<Customer> listCustomers = new List<Customer>();
                listCustomers.Add(new Customer { CustomerId = 1, CustomerName = “Customer1” });
                listCustomers.Add(new Customer { CustomerId = 2, CustomerName = “Customer2” });
                listCustomers.Add(new Customer { CustomerId = 3, CustomerName = “Customer3” });
                listCustomers.Add(new Customer { CustomerId = 4, CustomerName = “Customer4” });
                var viewmodel = new ProductsViewModel
                {
                    Products = product,
                    Customers = listCustomers
                };
                return View(viewmodel);
            }
            catch (Exception)
            {
                throw;
            }
        }

2. OnException method

You can use OnException method in a controller to handle exception for more than one Action method.

If you have used try-catch, you may have noticed that try-catch block is required at every Action method to cover exceptions.

But in this case, only one OnException method is enough to handle exception which may occur at any Action method in a Controller.

Below is the sample code to demonstrate OnException method.

public ActionResult DisplayProductName()
        {
            int j = 0;
            int i = 10 / j;
            return View();
        }
        protected override void OnException(ExceptionContext filterContext)
        {
            base.OnException(filterContext);
            filterContext.ExceptionHandled = true;
            filterContext.Controller.ViewBag.ErrorMessage = filterContext.Exception.Message;
            filterContext.Result = View(“Error”);
        }

OnException method is an overridden method which takes ExceptionContext as a  parameter and returns nothing.

You can assign Error message to the viewbag at this line and same will be accessed on the View page.

filterContext.Controller.ViewBag.ErrorMessage = filterContext.Exception.Message;

 
In below line, Error is the name of the view that I have created to display the error message.
filterContext.Result = View(“Error”);
Sample View page to display error message thrown by Action class.

    <div>
        <h2>Something went wrong while process your request. Here is the exception details.</h2>
        <p>
            @ViewBag.ErrorMessage
        </p>
    </div>

3. Exception Handling in MVC using filters

In Exception Filter, we implement the class with IExceptionFilter which contains only method – OnException and takes ExceptionContext as a parameter.
If you are using Exception filter, you have to apply filter class name as an attribute to the particular Action method.

I have already written a blog on Filters in MVC. Request you to read the blog on Filters.

4. HandleError Class

HandleError class implements IExceptionFilters interface.
We can apply HandleError as an attribute to an Action method or to a Controller class, which will enable exception handling for all the Action methods within that Controller class.

HandleError attribute to an Action method

 [HandleError]
        public ActionResult DisplayProductName()
        {
            int j = 0;
            int i = 10 / j;
            return View();
        }

HandleError attribute to Controller class, which is applicable on all Action methods within this Controller class.

     [HandleError]
    public class ProductController : Controller
    {
        public ActionResult DisplayProductName()
        {
            int j = 0;
            int i = 10 / j;
            return View();
        }
    }

5. Application_Error for MVC Global handling

Application_Error method can be found in Global.asax file and it executes whenever an error occurred at any point in the application. This is not new to MVC, this process is very old and .Net developers have been using this for a very long time.

Application_Error() method in Global.asax file

     public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Error()
        {
            //Write your custom logic
        }
    }

You may also like below blogs on ASP.Net MVC

Leave a Comment

RSS
YouTube
YouTube
Instagram