How to use HandleError in MVC 3 [With Example]

To enable custom errors, we’ll need to set the customErrors property to ‘on’.

1. Web.config

<system.web>
    <customErrors mode="On">
    </customErrors>
</system.web>

2. Exception in controller

Below in the controller, the controller class is decorated with the HandleError attribute and I have thrown an exception to test this out.

[HandleError]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        throw new Exception("Error Occured !");
        ViewBag.Message = "Welcome to ASP.NET MVC!";
        return View();
    }

    public ActionResult About()
    {
        return View();
    }
}

3. Error.chtml

In the screenshot below, I have added a razor view Error.cshtml, do note that this view uses a model of type System.Web.Mvc.HandleErrorInfo.

enter image description here

@model System.Web.Mvc.HandleErrorInfo @{ ViewBag.Title = "Error"; }
<h2> Sorry, an error occurred while processing your request. </h2>

Now when we run the project and the exception we wrote will be raised, but instead of getting the YSOD we now get the following customized error message.

enter image description here

We can customize this view and get more meaningful message to our fellow devs in the following manner…

@model System.Web.Mvc.HandleErrorInfo 
@{ ViewBag.Title = "Error"; }
<h2> Sorry, an error occurred while processing your request. </h2> 

@if (Model != null)
{
    <p>Controller Name: @Model.ControllerName</p> 
    <p>Action Name : @Model.ActionName</p> 
    <p> 
        <p>Exception Details: @Model.Exception.Message</p> 
        <p>Source:@Model.Exception.Source</p> 
        <p>Stack Trace:@Model.Exception.StackTrace</p> 
        <p>InnerException:@Model.Exception.InnerException</p>
    </p>
}

and the output

enter image description here

Hope you found this helpful !