How to Handle ‘Not Found’ in Rails
Transitioning to Rails after Sinatra was pretty smooth since they have a lot in common, MVC in particular. The Big difference I wanna say was a division of routes from controllers but besides the fact that rails is way more advanced and have over 200,000 lines of code in its engine vs 2,000 lines in Sinatra’s. Doing the Sinatra project I really liked that you can just write
and it handles it for you.
In Rails, It’s not much more complicated but you can approach it from many angles if you’d like, from throwing an error message to rendering a view that suits your website. I wanna share with you the approach I decided to go with for my Rails project.
First, let’s start with the routes:
and now let’s talk about what this line of code means:
match — is connected to the next part of code that says via: all which would be equivalent of saying via: [:get, :post] so it matches any post or get requests.
“*any” — using a wildcard and any says that it should catch any routes that aren’t declared and send them to a specific controller and action to handle
to: “errors#not_found” — means that handling it will be our errors controller in not_found action that we will create in a second.
So what we have now is any URL on our website routes of which aren’t specified will be sent to an errors controller so let’s create one.
Here we created an errors_controller.rb in our controllers file, added class ErrorsController that inherit from the application controller and defined not_found action, also specified layout for this controller as my “welcome” layout that doesn’t have any functionality or nav bars. So there is not logic in the action is added, which you can do something like:
to handle the errors but I decided to keep it blank and just create a errors view to nicely display the error message, meaning we’re going back this
and let’s create an errors folder inside of the views and create a not_found.html.erb as well
I used a bootstrap to style it out a bit and this is how it renders in my web app:
Thank you for reading!