2

In Visual Studio 2012 I created a new ASP.NET MVC3 Project using the Empty template. Then I created a HomeController with the following ActionResult:

public ActionResult Index()
{
    throw new Exception("oops!");
    ViewBag.Message = "hello world";
    return View();
}

Next, I added a simple view for my HomeController:

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

and inserted the following in the {root}/web.config:

<customErrors mode="On"/>

Finally, I modified /Views/Shared/Error.cshtml to look like:

@model System.Web.Mvc.HandleErrorInfo
@{
    //Layout = null;
    ViewBag.Title = "Error";
}

<h2>
    Sorry, an error occurred while processing your request.
</h2>

When I run the project I get:

500 Internal Server Error. The website cannot display the page...

Then I decided to create another ASP.NET MVC3 Project using the Internet template. Inside the HomeController I throw an Exception exactly like I did above and I turned on customErrors again in the Web.config. When I run the project I get the correct results:

Sorry, an error occurred while processing your request.

What could I be missing between the two projects?

I've went line by line through the Web.config and didn't see any differences. The Global.asax file was untouched with both projects.

lhan
  • 4,585
  • 11
  • 60
  • 105
Zach L
  • 1,277
  • 4
  • 18
  • 37

2 Answers2

1

I can't believe this...

Thanks to Cosmin Onea comment below he had me inherit from HandleErrorAttribute and OnException was being fired as it should. After making that change I ran across this SO answer and tested my page in Chrome where I see the appropriate message that has been there the whole time.

Although I'm still confused why one runs just fine in IE and the other application doesn't.

Community
  • 1
  • 1
Zach L
  • 1,277
  • 4
  • 18
  • 37
0

You need to register the HandleErrorAttribute as a global filter.

In your Global.asax, in the Application_Start event register the filter:

    protected void Application_Start()
    {
        ...
        RegisterGlobalFilters(GlobalFilters.Filters);
        ....
    }

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }

You can also apply the filter to a controller or an action directly. What the filter does, in case of an exception, it sets the Result on the filterContext to point to your Error view.

Cosmin Onea
  • 2,698
  • 1
  • 24
  • 27