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

问题描述

我正在为 Rails3 应用程序添加一个 API,并且进展顺利.但是我在 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"
     }
   ]
 }

我喜欢错误消息结构.但无法让它重现.我怎样才能让我的 apis 做出像这样的响应?

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?

推荐答案

通过为 JSON 格式添加 ActionController::Responder,您可以很容易地实现该错误格式.见 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:Responder 中的私有方法,该方法将构造 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

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

08-23 17:32