How to Handle error in ASP.NET MVC?

Updated on     Kisan Patel

This post will explain you how to handle error for controller action method and redirect the user to
a default error page?

To handle the error for the controller action method, first set the customError mode “on” under system.web in the root web.config file.

    <customErrors mode="On"/>

When the customErrors mode is “On”, any unhandled error redirects to the default error view that is under ~/Views/Shared/Error.cshtml

So lets add Error.cshtml view inside ~/Views/Shared/ and add following code

@model System.Web.Mvc.HandleErrorInfo
    ViewBag.Title = "Error";
<hgroup class="title">
    <h1 class="error">Error.</h1>
    <h2 class="error">An error occurred while processing your request.</h2>
    Controller: @Model.ControllerName
    Action: @Model.ActionName
    Exception: @Model.Exception

In the above view, the model is System.Web.Mvc.HandleErrorInfo that holds the error exception details like ControllerName, ActionName in which error occurred and what error occurred.

Above functionality will work only when below settings remains intact in ~/App_Start/FilterConfig.cs page.

public class FilterConfig
   public static void RegisterGlobalFilters(GlobalFilterCollection filters)
       filters.Add(new HandleErrorAttribute());


protected void Application_Start()

Now, lets test the above configuration code by adding below error action method into HomeController

public ActionResult HandleError()
       int i = 0;
       var result = 1 / i;
       return View();

Above controller method will throw error and because customErrors mode is set to “On” in web.config file so user gets redirected to below view page under Shared folder.


Download Source Code


Leave a Reply