开发者

Api errors customization for Rails 3 like Github api v3

开发者 https://www.devze.com 2023-03-03 23:03 出处:网络
I am adding an API on a Rails3 app and its pretty going good. But I saw the following Github api v3 at http://developer.github.com/v3/

I am adding an API on a Rails3 app and its pretty going good. But I saw the following Github api v3 at http://developer.github.com/v3/

HTTP/1.1 422 Unprocessable Entity
 Content-Length: 149

 {
   开发者_JS百科"message": "Validation Failed",
   "errors": [
     {
       "resource": "Issue",
       "field": "title",
       "code": "missing_field"
     }
   ]
 }

I liked the error messages structure. But couldn't get it to reproduce. How can I make my apis to make the response like it?


You could quite easily achieve that error format by adding an ActionController::Responder for your JSON format. See http://api.rubyonrails.org/classes/ActionController/Responder.html for the (extremely vague) documentation on this class, but in a nutshell, you need to override the to_json method.

In the example below I'm calling a private method in an ActionController:Responder which will construct the json response, including the customised error response of your choice; all you have to do is fill in the gaps, really:

def to_json
  json, status = response_data
  render :json => json, :status => status
end

def response_data
  status = options[:status] || 200
  message = options[:notice] || ''
  data = options[:data] || []

  if data.blank? && !resource.blank?
    if has_errors?
      # Do whatever you need to your response to make this happen.
      # You'll generally just want to munge resource.errors here into the format you want.
    else
      # Do something here for other types of responses.
    end
  end

  hash_for_json = { :data => data, :message => message }

  [hash_for_json, status]
end
0

精彩评论

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