JSON API response for 'No route matches'
In your routes.rb
, add the last line
MyAppApi::Application.routes.draw do
# omitted lines
match '*a', :to => 'errors#routing'
end
NOTE: The "a" is actually a parameter in the Rails 3 Route Globbing technique. For example, if your url was /some-random-path, then params[:a] equals "some-random-path". But notice the preceding slash is not there. To mock the actual path, I used request.path
instead.
Create errors_controller.rb
that inherits from application_controller.rb
class ErrorsController < ApplicationController
def routing
not_found(ActionController::RoutingError.new("No route matches [#{request.method}] #{request.path}"))
end
end
The exception will throw the message similar to a typical no route message, with the method
and the requested path
Then, In your application_controller.rb
, add the not_found
action
class ApplicationController < ActionController::Base
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
def not_found(exception)
respond_to do |format|
format.json { render :json => {:error => exception.message}, :status => :not_found }
format.any { render :text => "Error: #{exception.message}", :status => :not_found }
end
end
end
The client will get this json
response for non-routable path
{
error: "No route matches [GET] /groups/cf8260ab-a431-4e40-8520-a8d24c681639/join"
}
Written by Marvin Marcelo
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#