Custom Errors in ASP.Net MVC: It couldn't be simpler, right?
secretGeek .:dot Nuts about dot Net:.
home .: about .: sign up .: sitemap .: secretGeek RSS

Custom Errors in ASP.Net MVC: It couldn't be simpler, right?

parallaxing 404 at github

Cool looking 404 pages are the new hotness. Github has an amazing parallaxing 404 page that allegedly cost more than any other feature on their site.

For a lot of sites, the 404 page is the most visited page, so it's worth getting it right.

The website for my new product, NimbleText, uses asp.net mvc. A framework I really enjoy. The gu wrote it on a plane. Before takeoff.

One of the more voodoo aspects of getting NimbleText.com into production was setting up a succesful custom 404 page. Here's what I came up with: check it out.

Some of the articles out there that cover custom errors in asp.net MVC seemed to be a little bit confused about exactly what is going on, many are out of date or incomplete and some are downright misleading.

So once and for all I want to give a definitive guide to error handling in asp.net MVC.

Here we are. Just eleven simple steps to follow for amazing results.

First, map a catch-all route in global.asax, at the end of your other routes. E.g.

routes.MapRoute(
   "404-PageNotFound",
   "{*url}",
   new { controller = "StaticContent", action = "PageNotFound" }
);

Second, create an Error Controller, like this:

public class ErrorController : Controller
{
   [AcceptVerbs(HttpVerbs.Get)]
   public ViewResult Unknown()
   {
     Response.StatusCode = (int)HttpStatusCode.InternalServerError;
     return View("Unknown");
   }

   [AcceptVerbs(HttpVerbs.Get)]
   public ViewResult NotFound(string path)
   {
     Response.StatusCode = (int)HttpStatusCode.NotFound;
     return View("NotFound", path);
   }
}

Third and fourth -- create custom views to handle the Unknown and NotFound actions above.

Fifth, create a page called Custom404.htm and add it to the root of your application. Use it to display a helpful, edgy and hopefully cool message. But don't be too edgy.

Sixth, add this to web.config, inside the system.web node:

<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
   <error statusCode="404" redirect="/Custom404.htm" />
</customErrors>

Seventh, add a httpErrors element inside the system.webServer node:

<httpErrors>
   <error statusCode="404" subStatusCode="-1" path="/custom404.htm" responseMode="Redirect" />
</httpErrors>

Eighth, inside your existing controllers, if there is no data to serve (e.g. if someone asks for a UserId that doesn't exist) then use this snippet of code:

throw new HttpException(404);

Ninth, inside Global.asax, look for the RegisterGlobalFilters method (it will be called during Application_Start), and add another global filter, to handle any specific exceptions in your code, like this:

filters.Add(new HandleErrorAttribute
    {
        ExceptionType = typeof(FileNotFoundException),
        View = "Custom404", // Custom404.cshtml is a view in the Shared folder.
        Order = 2
    });

Tenth, add a view called Custom404.cshtml under views/shared.

And, eleventh, take care to handle the global application error event, capturing and logging any errors, before redirecting to the views you're after:

protected void Application_Error(object sender, EventArgs e)
{
    Exception exception = Server.GetLastError();
    Response.Clear();
    HttpException httpException = exception as HttpException;
    if (httpException != null)
    {
        string action;
        switch (httpException.GetHttpCode())
        {
            case 404:
                // page not found
                action = "HttpError404";
                break;
            case 500:
                // server error
                action = "Internal500";
                break;
        default:
            action = "General";
            break;
        }
        // clear error on server
        Server.ClearError();
        Response.Redirect(String.Format("~/Error/{0}/?message={1}", action, exception.Message));
    }
}
unexpected error

Good.

Now your website is well and truly borked.

Every request will bounce around your application like a demented pinball tripping on acid.

When an error happens, a bunch of different code modules will go to war.

The victorious code module will tear out the entrails of all those who oppose it, and throw them in the visitor's face.

You'll get a different error handler depending on what version of IIS you have, what version of MVC you're using, whether you've deployed in debug or release, whether you're visiting locally or remotely, whether it's sunny or raining.

Your server will be reduced to a pile of smouldering rubble from which reboot is impossible.

But if you want to get truly weird, try setting up a custom 403 page. That's about three times as odd.

Or, switch to Dos on Dope*. Life will be simple again.

Sorry I didn't really have time to write a definitive guide to this stuff. Error handling in MVC is crazy man, I'm busy fighting a clandestine war against hackers and crackers and bots and beuracrats: I can't be documenting that kind of mystery wrapped in an enigma.

If someone does write a complete guide to error handling in MVC, that includes the meaning and interaction behind each of these snippets, plus how the interplay between IIS, asp.net and MVC truly works, then I will happily update this article to include a link to it, right up top.


* Don't switch to Dos On Dope.





'troy' on Wed, 15 Jun 2011 08:53:49 GMT, sez:

This really is too hard.



'lb' on Mon, 25 Jul 2011 04:02:44 GMT, sez:

The other thing to do, in your errorcontroller is to add this:

Response.TrySkipIisCustomErrors = true;

That way asp.net will handle the error rather than iis taking over.



'Alan Stevens' on Sun, 25 Sep 2011 23:47:02 GMT, sez:

Leon, have you seen this?

http://nuget.org/List/Packages/MagicalUnicornMvcErrorToolkit

Are you to blame?

++Alan



'Bilal' on Thu, 17 Nov 2011 18:22:14 GMT, sez:

Complete worthless!

I tried to implement all of above and got compile error, i corrected them and then tried to access non existing pages or product id's and got the usual yellow asp.net error page, that is none of the custom error pages where shown!!!

Please before putting up and article like this. Try to implement it and see whether it is working. Otherwise you are just wasting our time.




'Sumit' on Tue, 05 Jun 2012 05:44:20 GMT, sez:

I think the Catch-All route should be referring to 'ErrorController' instead of 'StaticContentController' so it should read

routes.MapRoute(
"404-PageNotFound",
"{*url}",
new { controller = "Error", action = "NotFound" }
);

?

Nice summary though!



'Will S.' on Mon, 13 Aug 2012 19:35:40 GMT, sez:

@lb: That won't work if you have validateIntegratedModeConfiguration set to "false", like I do. Kind of need that for my web sites for my web handlers.



'Will S.' on Mon, 13 Aug 2012 19:41:40 GMT, sez:

I meant "my web site's web handlers".



'Robert' on Thu, 20 Dec 2012 17:43:41 GMT, sez:

Dude, you do not know how to use ASP.NET.

You are not meant to use a redirect inside <customErrors> of the web.config and have a handle error attribute in the RegisterGlobals at the same time.

These are two seperate implementations of a similar thing.

The reason you had such a hard time getting it to work is because you had to write a lot of extra code to make them stop fighting with each other.


A custom error handler is as simple as a change to the web.config:

<customErrors mode="On">
<error statusCode="404" redirect="/Error/404" />
</customErrors>

(and any other status you want to handle)

Then, Make sure that your globals does NOT add a filter for HandleErrorAttribute under RegisterGlobalFilters.

Now your redirect is done.
If you want to try to capture extra info, you can do that as you were inside Application_Error in the globals file.

OR... you can not include the redirect in the Web.config, and you can include the filter, and write the Error controller.

There is no need to do both.



'guillegr123' on Tue, 14 May 2013 23:37:42 GMT, sez:

Seems to be all the ways one can implement custom errors in ASP.NET MVC... But I think you cannot implement all the solutions at the same time :S



'David' on Wed, 16 Oct 2013 00:54:12 GMT, sez:

It took me three reads to be sure, but the author was not attempting to tell us how to do it. He was telling us how to really mess up our system by following all the confused advice, and said so. I personally just had some difficulty reading the tenor of his snark (was he really saying it would bork your system, or was he being ironic?).

Anyway, Roboert, while missing the snark, did provide an answer that works for real. Thanks Robert!

For the moment, the config capture of non-500 errors, combined with the default error handling attribute seems to work. I get to my custom controller error view for the 404 (etc.), but I go to the MVC Shared/Error.cshtml for thrown exceptions. Combined with ELMAH.MVC, I think I'm on the road to an effective error handling design. I might remove the filter and go completely custom, or I might not. Time will tell.



'lb' on Wed, 16 Oct 2013 01:06:16 GMT, sez:

@David
Yeh, it is all meant as snark. Just re-reading it now I am amazed by the whole thing. I'm not usually this psychotic, handing out such a deviously crafted piece of confusion.

Robert's answer is great, because he works through his frustration and gives a nice simple solution.




name


website (optional)


enter the word:
 

comment (HTML not allowed)


All viewpoints welcome. Incivility is not tolerated, such comments are deleted.

 

I'm the co-author of TimeSnapper, a life analysis system that stores and plays-back your computer use. It makes timesheet recording a breeze, helps you recover lost work and shows you how to sharpen your act.

 

NimbleText - FREE text manipulation and data extraction

NimbleText is a Powerful FREE Tool

I wrote this, and use it every day for:

  • extracting data from text
  • manipulating text
  • generating code

It makes you look awesome. You should use NimbleText, you handsome devil!

 

Articles

The Canine Pyramid The Canine Pyramid
Humans: A Tragedy. Humans: A Tragedy.
ACK! ACK!
OfficeQuest... Gamification for the Office Suite OfficeQuest... Gamification for the Office Suite
New product launch: NimbleSET New product launch: NimbleSET
Programming The Robot from Diary of a Wimpy Kid Programming The Robot from Diary of a Wimpy Kid
Happy new year 2014 Happy new year 2014
Downtime as a service Downtime as a service
The Shape of Your Irrationality The Shape of Your Irrationality
This is why I don't go to nice restaurants any more. This is why I don't go to nice restaurants any more.
A flowchart of what programmers do at work all day A flowchart of what programmers do at work all day
The Telepresent Man. The Telepresent Man.
Interview with an Ex-Microsoftie. Interview with an Ex-Microsoftie.
CRUMBS! Commandline navigation tool for Powershell CRUMBS! Commandline navigation tool for Powershell
Little tool for making Amazon affiliate links Little tool for making Amazon affiliate links
Extracting a Trello board as markdown Extracting a Trello board as markdown
hgs: Manage Lots of Mercurial Projects Simultaneously hgs: Manage Lots of Mercurial Projects Simultaneously
You Must Get It! You Must Get It!
AddDays: A Very Simple Date Calculator AddDays: A Very Simple Date Calculator
Google caught in a lie. Google caught in a lie.
NimbleText 2.0: More Than Twice The Price! NimbleText 2.0: More Than Twice The Price!
A Computer Simulation of Creative Work, or 'How To Get Nothing Done' A Computer Simulation of Creative Work, or 'How To Get Nothing Done'
NimbleText 1.9 -- BoomTown! NimbleText 1.9 -- BoomTown!
Line Endings. Line Endings.
**This** is how you pivot **This** is how you pivot
Art of the command-line helper Art of the command-line helper
Go and read a book. Go and read a book.
Slurp up mega-traffic by writing scalable, timeless search-bait Slurp up mega-traffic by writing scalable, timeless search-bait
Do *NOT* try this Hacking Script at home Do *NOT* try this Hacking Script at home
The 'Should I automate it?' Calculator The 'Should I automate it?' Calculator

Archives Complete secretGeek Archives

TimeSnapper -- Automated Screenshot Journal TimeSnapper: automatic screenshot journal

25 steps for building a Micro-ISV 25 steps for building a Micro-ISV
3 minute guides -- babysteps in new technologies: powershell, JSON, watir, F# 3 Minute Guide Series
Universal Troubleshooting checklist Universal Troubleshooting Checklist
Top 10 SecretGeek articles Top 10 SecretGeek articles
ShinyPower (help with Powershell) ShinyPower
Now at CodePlex

Realtime CSS Editor, in a browser RealTime Online CSS Editor
Gradient Maker -- a tool for making background images that blend from one colour to another. Forget photoshop, this is the bomb. Gradient Maker



[powered by Google] 

How to be depressed How to be depressed
You are not inadequate.



Recommended Reading


the little schemer


The Best Software Writing I
The Business Of Software (Eric Sink)

Recommended blogs

Jeff Atwood
Joseph Cooney
Phil Haack
Scott Hanselman
Julia Lerman
Rhys Parry
Joel Pobar
OJ Reeves
Eric Sink

InfoText - amazing search for SharePoint
LogEnvy - event logs made sexy
Computer, Unlocked. A rapid computer customization resource
Aussie Bushwalking
BrisParks :: best parks for kids in brisbane
PhysioTec, Brisbane Specialist Physiotherapy & Pilates
 
home .: about .: sign up .: sitemap .: secretGeek RSS .: © Leon Bambrick 2006 .: privacy

home .: about .: sign up .: sitemap .: RSS .: © Leon Bambrick 2006 .: privacy