0

Can someone explain me how to add custom 404 and 500 Errors to my project? I tried by adding this to Web.config:

<customErrors mode="On">
    <error code="404" path="404.html" />
    <error code="500" path="500.html" />
</customErrors>
IvanD
  • 157
  • 4
  • 12

2 Answers2

0

The OnException method gets invoked if an action method from the controller throws an exception. Unlike the HandleErrorAttribute it will also catch 404 and other HTTP error codes and it doesn't require customErrors to be turned on.

It is implemented by overriding the OnException method in a controller:

protected override void OnException(ExceptionContext filterContext)
{
filterContext.ExceptionHandled = true;

// Redirect on error:
filterContext.Result = RedirectToAction("Index", "Error");

// OR set the result without redirection:
filterContext.Result = new ViewResult
{
    ViewName = "~/Views/Error/Index.cshtml"
};
}

With the filterContext.ExceptionHandled property you can check if an exception has been handled at an earlier stage (e.g. the HandleErrorAttribute):

if (filterContext.ExceptionHandled) return; Many solutions on the internet suggest to create a base controller class and implement the OnException method in one place to get a global error handler.

However, this is not ideal because the OnException method is almost as limited as the HandleErrorAttribute in its scope. You will end up duplicating your work in at least one other place.

Mohan
  • 907
  • 5
  • 22
  • 45
0

This is the best article I have read recently that let's you know the joys you are about to get into http://benfoster.io/blog/aspnet-mvc-custom-error-pages and my customErrors element looks like this.

 <customErrors mode="Off" redirectMode="ResponseRewrite">
  <error statusCode="404" redirect="/404.aspx" />
  <error statusCode="500" redirect="/500.aspx"/>
</customErrors>
etoisarobot
  • 7,684
  • 15
  • 54
  • 83