我在一个rails应用程序上添加了一个API,并且进展得很顺利。但我看到以下Github api v3在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做出这样的响应呢?
你可以很容易地通过为JSON格式添加ActionController::Responder来实现这个错误格式。请参阅http://api.rubyonrails.org/classes/ActionController/Responder.html获取该类的(非常模糊的)文档,但简而言之,您需要重写to_json方法。
在下面的例子中,我在ActionController:Responder中调用一个私有方法,它将构造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