Last Updated: June 15, 2020
·
9.433K
· rshetty

Handling Exceptions in your Rails Application

Handling Exceptions in your Rails Application is very important both when you are developing a full stack web application with Rails as backend or exposing REST API's with Rails.

So here I am gonna walk you through handling some exceptions in your Rails application specifically when developing REST API's.

So first and foremost dont use these in your Application.....

rescue_from ActionController::RoutingError, with: :route_not_found
rescue_from ActionController::ActionNotFound, with: :action_not_found

Both of them dont work. Yeah, you heard me right they dont work.

So here is a workaround I have proposed which is used for handling RoutingError in your Application

WORKAROUND FOR ROUTINGERROR

# Add this in your config/routes.rb
match '*path', :to => 'application#routing_error'

And

# Add this to your application_controller.rb
def routing_error(error = 'Routing error', status = :not_found, exception=nil)
render_exception(404, "Routing Error", exception)
end

This basically matches any path other than the standard routes, so whenever you hit upon a non route, you will be redirected to the application#routing_error where you can render the exception.

WORKAROUND FOR ACTIONNOTFOUND

To handle the ActionNotFound Exception in your application, you have to override the 'action_missing' method in your application controller.

def action_missing(m, *args, &block)
  Rails.logger.error(m)
  redirect_to '/*path'
end

Disclaimer : You can use 'methodmissing' too, but this wont be supported in Rails 4.0, So it is safer to go with 'actionmissing'

This method will be called when a user tries to access an action which has not been defined or is missing. In this I am trying to redirect to a non route which results in routing_error to be called, thus handling the ActionNotFound with routing error.

Happy Hacking!!!

Thanks for reading...

Please Let me know if you have any other workarounds for the same.

3 Responses
Add your response

Thanks for this blog post! I was beginning to get suspicious of some other solutions out there and this really helped clarify what was going on. One comment, did you mean AbstractController::ActionNotFound instead of ActionController::ActionNotFound?

over 1 year ago ·

Thanks! Good writeup! I also had to specify the method to make Rails 4 happy:
match '*path', :to => 'application#routing_error', via: [:get, :post]

over 1 year ago ·

nice post. please explain about 'render_exception(404, "Routing Error", exception)'

over 1 year ago ·