API错误定制了对Rails 3像Github的API V3 [英] Api errors customization for Rails 3 like Github api v3

查看:127
本文介绍了API错误定制了对Rails 3像Github的API V3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Rails3中的应用程序添加API和pretty去好。
但我看到在 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

 {
   "message": "Validation Failed",
   "errors": [
     {
       "resource": "Issue",
       "field": "title",
       "code": "missing_field"
     }
   ]
 }

我喜欢的错误信息结构。但不能让它重现。
我怎样才能让我的API,使喜欢它的反应?

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?

推荐答案

您可以很容易地通过添加的ActionController ::响应您的JSON格式实现这一错误格式。请参见 http://api.rubyonrails.org/classes/ActionController/Responder.html对于这个类的(非常暧昧)的文件,但简而言之,你需要重写to_json方法。

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.

在下面,我呼吁在ActionController的私有方法的例子:响应,这将构建JSON响应,包括您所选择的自定义错误响应;你所要做的就是填补空白,真正做到:

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

这篇关于API错误定制了对Rails 3像Github的API V3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆