Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I handle errors or bad requests in my Rails REST API?

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?

like image 252
Kyle Kaitan Avatar asked Jul 29 '10 00:07

Kyle Kaitan


2 Answers

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!

like image 93
Geoff Lanotte Avatar answered Oct 17 '22 07:10

Geoff Lanotte


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
like image 22
ngoozeff Avatar answered Oct 17 '22 08:10

ngoozeff