The way to tell your MVC controller to use the Error view
for errors is to add the HandleError
attribute to it. HandleError is an ActionFilter that can be used to specify
how the controller (or action) should respond to any unhandled exceptions that
may occur. You should also configure error handling in your configuration file
by adding a <customErrors /> section to your <system.web />
section. While testing, you can set the mode to "On" or
"Off", and in production you'll likely want the mode to be
"RemoteOnly". Note that these are case-sensitive.
If you have customErrors mode set to Off, then HandleError
won't actually do anything, and you'll continue to see the YSOD when errors
occur in your application. However, when you set customErrors mode to On,
you'll start to see the correct behavior, which is a 500 error result and the
custom error page (by default /Views/Shared/Error.cshtml but it will also
search for other Views named Error in non-shared folder).
Listing 2 shows how to apply the HandleError attribute to
two controller action methods. When customerErrors is set to On, the first one
will display the default Error.cshtml view and the second will display the MyErrorView.cshtml
view.
Listing 2
[HandleError]
public ActionResult CreateErrorTwo()
{
throw new Exception("Using HandleError Attribute.");
}
[HandleError (View="MyErrorView")]
public ActionResult CreateErrorThree()
{
throw new Exception("Using HandleError Attribute and MyErrorView.");
}
You can also specify different ways to handle errors based
on the type of the exception by setting the ExceptionType parameter on HandleError.
The attribute also supports an Order parameter, which will control the order in
which the attributes are fired (highest number first, apparently, despite what
the docs say). Listing 3 shows how you can stack multiple HandleError
attributes on a single action (and note that you can also apply the attribute
at the Controller/class level).
Listing 3
[HandleError(View = "MyErrorView",
ExceptionType = typeof(NotImplementedException), Order=2)]
[HandleError(View = "Error", Order=1)]
public ActionResult CreateErrorFour(int id)
{
if(id < 0)
throw new NotImplementedException("id < 0");
throw new Exception("id >= 0");
}