views:

42

answers:

2

I have a Rails app that includes a JSON API interface. When values are properly specified, the controller handles the happy path just fine and JSON is rendered as output.

However, if there's a problem with the input, an exception is raised and some templates in rescues are rendered instead. I'd really just like to return a JSON error along the lines of { "error": { "msg": "bad request", "params": ... } } and the appropriate HTTP status code (e.g. 403 if they weren't authenticated). But I only want this to be applicable to requests against anything in example.com/api/....

How can I do that?

+1  A: 

How about an around_filter on your api controller. Something like

around_filter :my_filter

private
def my_filter
  begin
    yield
  rescue
    render :js => ...
  end
end
ngoozeff
+1  A: 

I had a similar case, but I rescued the individual API methods separately because I needed method specific errors, I also could have multiple rescues depending on the error type.

in my application controller, I had a method:

def error(status, code, message)
  render :js => {:response_type => "ERROR", :response_code => code, :message => message}.to_json, :status => status
end

Then in my API controller

def some_method
  ## do stuff
rescue
  error(500, method_specific_error_code, "it all done broke")
  ## additional error notifications here if necessary.
end

because I rescue the error, I needed to explicitly call to the hoptoad api.

To handle authentication, I had a before_filter for login_required

def login_required
  error(403, 403, "Not Authenticated") unless authenticated
end

And to rescue 404 errors:

def render_404
  error(404, 404, "Unknown method")
end

I hope this helps!

Geoff Lanotte
@geoff I too agree with you on this as this is the best way to render custom errors also for different actions
Hitesh Manchanda