How to handle exceptions in Rails 5

Problem

The bots make requests to rubyplus.com podcast section that results in ActionController::RoutingError in the log files. I can see the stack trace, the bot sees an error page. Ideally what I would like to do is to handle the exception so that I can still see that it happened in the log file and notify the bot that I don't have anything for that URL request. Basically the Rails app should not crash.

Solution

Add this:

rescue_from ActionController::RoutingError do |exception|
 logger.error 'Routing error occurred'
 render plain: '404 Not found', status: 404 
end

to the application controller. Add the catch all route in routes.rb:

match "*path", to: "welcome#catch_404", via: :all

In welcome controller, add catch_404 method.

def catch_404
  raise ActionController::RoutingError.new(params[:path])
end

If you see other exceptions such as missing template errors, you can do something similar.

rescue_from ActionView::MissingTemplate do |exception|
  logger.error exception.message
  render plain: '404 Not found', status: 404 
end

If the errors happen due to a user, you should show a meaningful message for a human and provide useful links on the page such as your recent podcast episode and most popular articles on your site. I don't think doing a redirect is a good idea. This article Rails' rescue_from shows how you can do that.

Summary

In this article, you learned how to handle exceptions caused by bots and what to render on the error page for a user vs a bot.


Related Articles


Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.