Tuesday, May 28, 2013

404 Errors in MVC Application

So MVC sites use routing to translate URLs into responses. This is a change from web forms. Web forms URLs are the location of actual assets. So the web server looks at the file path and figures out whether anything is there. With MVC it uses routing to try and create an controller object. So when you try to access a bogus path instead of the server not finding anything your application tries to turn this bogus path into a controller and throws an exception.

So this has implications as to your error handling. I am a big fan of doing error logging in HttpApplication.Application_Error and I hate it when you still try {...} catch (Exception e) { logError(e); throw; } everywhere. But this method will catch these exceptions which mask 404 errors. In the system I am currently working on every 404 would cause an error to be logged greatly irritating support staff. So the exception thrown is actually an HttpException. This exception has a method GetHttpCode that will return a 404 if the application is failing to build a controller out of a nonsense route. You can then use this to detect 404s.

No comments:

Post a Comment