To handle the error for the controller action method, first set the customErrors mode “on” under system.web in the root web.config file.
WEB.CONFIG FILE
<system.web> <customErrors mode="On"/> </system.web>
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.
CONTROLLER CODE
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.
VIEW 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> </hgroup> <p> Controller: @Model.ControllerName </p> <p> Action: @Model.ActionName</p> <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: 44446 | Post Order: 82