Custom Error Page for ASP.NET MVC 4

Posted on

Step 1: Custom Error page IIS 6. it helps for page not found (404) at http://www.example.com/someNotExistPage.html
Inside web.config
<system.web>
<customErrors mode=”On” defaultRedirect=”~/GenericErrorPage.html”/>
</system.web>

 
Step 2: Custom Error page IIS 7.5 it helps for page not found (404) at http://www.example.com/pathOne/pathTwo/someNotExistPage.html
Inside web.config
<system.webServer>

<httpErrors errorMode=”Custom” >
<remove statusCode=”404″ subStatusCode=’-1′ />
<remove statusCode=”500″  subStatusCode=’-1′ />
<error statusCode=”404″ path=”/GenericErrorPage.html” prefixLanguageFilePath=”” responseMode=”ExecuteURL”  />
<error statusCode=”500″ path=”/GenericErrorPage.html” prefixLanguageFilePath=”” responseMode=”ExecuteURL” />
</httpErrors>
……
</system.webServer>

Step 3: Inside the Global.asax for catching all exception in web application

protected void Application_Error(object sender, EventArgs e)
{
var httpApp = (HttpApplication)sender;
Exception exception = Server.GetLastError();
// log the exception
}

Step 4:
In the ASP.NET MVC 4 case must provide page at /Views/Shared/Error.cshtml
Inside App_Start …

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

And from Global.asax register it

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

….
}

If needed create CustomHandleErrorAttribute by extending HandleErrorAttribute and override OnException
and register it at global.aspx filter or manage like any other controller level attribute
e.g.

[CustomHandleError()]
public class AccountController: Controller
{
…..
}

 Step 5: If needed override controller OnException method at controller level

protected override void OnException(ExceptionContext filterContext)
{
base.OnException(filterContext);
….
}

If anything is missing please let me know.

Thanks & Regards,
-Vinayak B

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s