1

I'm using Rails as a JSON-only API server but whenever there is an exception in the a controller, say attempting to delete a record with an ID of 1 when it doesn't exist, Rails doesn't respond with JSON it responds with HTML, either a trace if in development or a generic 'something went wrong' page in production.

Right now I'm wrapping everything in a rescue and spitting out a JSON response manually...

class AmazonAccountsController < ApplicationController

  respond_to :json, :xml

  def destroy
    # Handle bad API calls.
    begin
      @account = AmazonAccount.find(params[:id])
      @account.destroy
      # unrelated code...
    rescue
      render :json => {:errors => {:bad => "ID doesn't exist."}}.to_json
    end
  end

end

but this doesn't seem like the ideal way to handle this.

This is in Rails 3.

4

1 回答 1

1

You're looking for rescue_from:

If you want to do something a bit more elaborate when catching errors, you can use rescue_from, which handles exceptions of a certain type (or multiple types) in an entire controller and its subclasses.

When an exception occurs which is caught by a rescue_from directive, the exception object is passed to the handler. The handler can be a method or a Proc object passed to the :with option. You can also use a block directly instead of an explicit Proc object.

So you could do something like this:

class ApplicationController < ActionController::Base
    rescue_from your_list_of_exceptions..., :with => :some_exception_handler
private
    def some_exception_handler
        render :json => { :error => 'some error message of some sort' }, :status => :unprocessable_entity # or whatever status makes sense.
    end
end

The API documentation on rescue_from is worth a look as well.

于 2012-07-15T05:09:14.637 回答