ruby - Rails 3 的 API 错误自定义,例如 Github api v3

标签 ruby ruby-on-rails-3 api

我在 Rails3 应用程序上添加了一个 API,它运行良好。 但我在 http://developer.github.com/v3/ 看到了以下 Github api v3

HTTP/1.1 422 Unprocessable Entity
 Content-Length: 149

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

我喜欢错误消息结构。但无法让它重现。 我怎样才能使我的 api 做出类似的响应?

最佳答案

您可以通过为您的 JSON 格式添加一个 ActionController::Responder 来轻松实现该错误格式。参见 http://api.rubyonrails.org/classes/ActionController/Responder.html对于此类的(非常模糊的)文档,但简而言之,您需要重写 to_json 方法。

在下面的示例中,我在 ActionController:Responder 中调用一个私有(private)方法,它将构建 json 响应,包括您选择的自定义错误响应;您所要做的就是填补空白,真的:

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

关于ruby - Rails 3 的 API 错误自定义,例如 Github api v3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5911470/

相关文章:

ruby-on-rails - Ruby on Rails - 轮胎 - elasticsearch,如何对导入的数据进行排序?

ruby-on-rails-3 - Rails 3 响应 header

api - 不同语言的雅虎天气

android - 尝试使用生成的 SDK 从 Android 进行 "Hello World"AWS API Gateway GET API 调用

node.js - 环回 3 中数据源的配置环境问题

mysql - 如何使用 mysql2 gem 创建准备好的语句?

Ruby,使用包含 TK GUI 的 ocra 部署一个 exe

ruby-on-rails - 将链接传递回 Rails 中的通知

datetime - Rails 中单独的日期和时间表单字段

ruby-on-rails-3 - 跨子域的 rails 3 session 在 Internet Explorer 中不起作用