a developer's notes – a semi-technical web development BLOG

August 28, 2014

Custom Error Pages in MVC 4

Filed under: Uncategorized — Duy Nguyen @ 11:52 am
Tags: , , , , , ,

Default solution: Use MVC HandleErrorAttribute

 

In MVC, by default, you will have in your Global.ascx, under Application_Start()

FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

And in RegisterGlobalFilters, you will have…

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

In your web.config, if you turn on custom errors like this…

<system.web>
    <!--<customErrors mode="On"></customErrors>-->
    <customErrors mode="On" defaultRedirect="myCustompage.html?"></customErrors>
</system.web>

customErrors mode=”On” = will turn on the default ~/Views/Shared/Error.cshtml view. (If you’re using IE, be sure to uncheck “Friendly Http Errors.” It works good but if you navigate to http://localhost/404, you will get the default yellow error screen unless you specify defaultRedirect=”myCustompage.htm”. Only then, will the application handle an internal application AND 404s, 500s, etc.

 Note: I’ve read lots of issues trying to preserve the error status code or the original stack trace

 

Alternative solution: Use Application_Error

 

You can also go the Application_Error route but will not have a backup error page if there is an error rendering the error page.

See this great blog post.
http://thirteendaysaweek.com/2012/09/25/custom-error-page-with-asp-net-mvc-4/

 

Some good other reads:

http://www.devcurry.com/2012/06/aspnet-mvc-handling-exceptions-and-404.html

http://colinmackay.co.uk/2011/05/02/custom-error-pages-and-error-handling-in-asp-net-mvc-3-2/

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

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

Create a free website or blog at WordPress.com.

%d bloggers like this: