Rails renders HTML when requesting JSON on error

I am using Rails as a JSON-only API server, but whenever there is an exception in the controller, try deleting the entry with id 1, if it doesn't exist, Rails doesn't respond JSON responds with HTML, either with a trace if in development or with a generic page " something does not work".

Right now, I'll wrap up to the rescue and spit out the 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 that doesn't seem like the ideal way to handle it.

This is in Rails 3.

+1


source to share


1 answer


You are looking for rescue_from

:

If you want to do something a little more sophisticated when catching errors, you can use rescue_from

one that handles exceptions of a specific type (or multiple types) across the entire controller and its subclasses.

When an exception is thrown that hits the directive rescue_from

, the exception object is passed to the handler. The handler can be a method or an object Proc

passed to a parameter :with

. You can also use a block directly instead of an explicit object Proc

.

So, you can 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 onrescue_from

is worth a look too.

+1


source







All Articles