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'
# Add this to your application_controller.rb
def routing_error(error = 'Routing error', status = :not_found, exception=nil)
render_exception(404, "Routing Error", exception)
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)
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.
Thanks for reading...
Please Let me know if you have any other workarounds for the same.