ASP.NET MVC > Error handling

Redirecting to default error page from controller action in ASP.NET MVC

How to handle error in controller action method and redirect the user to a default error page?

To handle the error for the controller action method, first set the customErrors 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

Let us see this in action. Write below code in controller.


public ActionResult HandleError()
    var i = 5;
    var j = 0;
    var sum1 = i / j;
    return View();

Above controller method will throw error becasuse we are trying to divide 5 by 0. Now because customErrors mode is set to “On” in web.config file so user gets redirected to below default view page under ~Views/Shared folder.


@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</p>
       Exception: @Model.Exception</p>

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 (that comes with default project) remains intact in ~/App_Start/FilterConfig.cs page.

public class FilterConfig
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        filters.Add(new HandleErrorAttribute());
 Views: 41141 | Post Order: 82

Write for us

Hosting Recommendations