开发者

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开发者_JAVA百科 { "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?


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!


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜