Lars Holdgaard
Lars Holdgaard

Reputation: 9966

Error page (response) is not shown when error occurs - customErrors is ON

I have a standard ASP.NET MVC application. Here I want to redirect all errors to a custom error page.

I have tried to set this up based on what I usually do + can Google, but still, I don't get the error.

I have the following web.config:

<system.web>
    <customErrors mode="On" defaultRedirect="~/Error/Index">
      <error redirect="~/Error/NotFound" statusCode="404" />
      <error redirect="~/Error/Index" statusCode="500" />

    </customErrors>
    <!-- More stuff :-) -->
  </system.web>
  <system.webServer>

This is my error controller:

 public class ErrorController : Controller
    {
        public ViewResult Index()
        {
            return View("Error");
        }
        public ViewResult NotFound()
        {
            Response.StatusCode = 404; 
            return View("NotFound");
        }
    }

I have the following FilterConfig:

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

However, when I create an error in my Index Controller:

    public ActionResult Index(InvoiceOverviewViewModel vm)
    {
        // used to test error pages :D
        int a = 5;
        int b = 0;
        int res = a / b;
    }

Which gives an error, I see the following:

enter image description here

While my Index.cshtml inside the ErrorController has the following view:

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_VerifyLayout.cshtml";
}

<h1>Danish text that doesn't make any sense here ;-) </h1>

What makes it even a bit more weird, is that my 404 page works. This page renders perfectly on localhost (not on production, however).

Any ideas?

Upvotes: 0

Views: 88

Answers (1)

CodeFuller
CodeFuller

Reputation: 31282

Problem #1:

While my Index.cshtml inside the ErrorController has the following view...

Your error view is named Index, but in in ErrorController you try to return unexisting view with name Error:

return View("Error");

Change ErrorController.Index() method to:

public ViewResult Index()
{
    return View("Index");
}

or call View() without arguments which will default to "Index":

public ViewResult Index()
{
    return View();
}

Problem #2:

filters.Add(new HandleErrorAttribute());

You should actually remove HandleErrorAttribute filter. This filter will process exception thrown by controller action, and it has its own logic for selecting result error view that will prevent display of your custom error page. Particularly, HandleErrorAttribute uses "~/Views/Shared/Error.cshtml". That's the source of error view you see - "An error occurred while processing your request."

Hope this will help. Here are some useful sources regarding error handling in ASP.NET MVC:

Upvotes: 1

Related Questions