Default Error Pages
Rails already comes with its own error pages which is okay but too simple, but we can add our own custom error pages, just to make it look a lot nicer, here’s a quick and easy way on how you can do that.
The default error pages that comes with rails are very minimal, just text based error pages with no images or animations, but these days we can see that a lot of websites use very creative error pages with great looking animations, for example you look at github’s error page or marvel’s error page below.
Adding Custom Error Pages
I always customize my error pages in all of my rails apps. To add custom error pages, there are a lot of beautiful and modern looking free templates that we can download and customize, some of them even have creative animations, or we can also create our own error pages from scratch.
Points to keep in mind, when creating/customizing the error pages
- if you are using images in your error pages, it’s better to encode it in base64 and use base64image, you can convert your images to base64 with lots of tools that you can find online, just search for ‘base64 image’ or when using SVGs, embed it directly don’t add links to external files.
- make sure to add/embed all the styles and scripts in the same html file, don’t use the asset pipeline.
So now after creating our own custom error pages
we can move those .html files to our rails app, on this directory
make sure to add/replace all of those pages
if you did everything correctly, it will now load your custom error pages. Please keep in mind that error pages will load in ‘production’ environment only, by default. You can quickly test your error pages by deploying your app to heroku.
There are additional steps that you can follow, if you want to see or test the error pages in ‘development’ environment, check the documentation on rails guides if you want to do so. I’ll be posting a tutorial sometime later on how to do that.
How to do it, the DRY way
The above method is a quick and easy way to add custom error pages, but not DRY (because if we wanted to make changes to those error pages, we have to make changes in each of those files individually), for a DRY approach we can create an ‘ErrorPages’ controller and then configure our ‘routes.rb’ file to match the /404, /422 and /500 requests. This way we can use our default application layouts and do a DRY approach. I’ll be posting a tutorial on how to do that too, So stay tuned and good luck with building your rails apps.