Is there a way to globally define a rails app to only serve json and xml and appropriately error on any other requests?
I'm thinking it's something along the lines of a before_filter and responds_to block in the ApplicationController but that's as far as my investigation has got me.
Just declare it at the class level on your controller, using respond_to
. It will apply to all your controllers if you do it on ApplicationController
class ApplicationController < ActionController::Base
respond_to :xml, :json
…
end
Also read about ActionController::Responder
class for more options.
To make json response on errors, just add the following code to your application_controller:
rescue_from Exception, :with => :render_error
rescue_from ActiveRecord::RecordNotFound, :with => :render_not_found
rescue_from ActionController::RoutingError, :with => :render_not_found
rescue_from ActionController::UnknownController, :with => :render_not_found
rescue_from ActionController::UnknownAction, :with => :render_not_found
private
def render_not_found(exception)
# logger.info(exception) # for logging
respond_to do |format|
render json: {:error => "404"}, status: 404
end
end
def render_error(exception)
# logger.info(exception) # for logging
respond_to do |format|
render json: {:error => "500"}, status: 500
end
end
public
def some_public_func
#do sthg
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With