custom 404 page for rails 3

10 Jan 2013

Handling exception in Rails 3.x is entirely different from Rails 2.x. In Rails 3.x, whole exception handling is moved to rack middleware stack. So we can't catch 404 and 500 exception from ApplicationContoller with rescue_from method.

Here is the simple way to handle 404 exceptions so that you can show custom page for them.

For that first we need to route the exception app to our own routes. Adding the following line of code to application.rb will do the trick.
Now all the exceptions will be routes to our routes. Next we need to add routes to handle those.
Now our route is ready. Please make sure that you use "match" for the route matching since we are expecting exception from every single http requests such as get/post/put/delete. Next thing is just a controller, action and view for the route.

Errors Controller

Not found view

Thats it. You have done. Now try to invoke a 404, you can view your custom 404 page.
Hope it helped you.
Happy coding. ;)

Photo Credit :
If you find my work useful, I appreciate donations via PayPal.
comments powered by Disqus