ruby – 像Github api v3一样为Rails 3定制Api错误

前端之家收集整理的这篇文章主要介绍了ruby – 像Github api v3一样为Rails 3定制Api错误前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在Rails3应用程序上添加了一个API,它非常好用.
但我在 http://developer.github.com/v3/看到了以下Github api v3
  1. HTTP/1.1 422 Unprocessable Entity
  2. Content-Length: 149
  3.  
  4. {
  5. "message": "Validation Failed","errors": [
  6. {
  7. "resource": "Issue","field": "title","code": "missing_field"
  8. }
  9. ]
  10. }

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

解决方法

您可以通过为JSON格式添加ActionController :: Responder来轻松实现该错误格式.有关此类的(极其模糊的)文档,请参阅 http://api.rubyonrails.org/classes/ActionController/Responder.html,但简而言之,您需要覆盖to_json方法.

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

  1. def to_json
  2. json,status = response_data
  3. render :json => json,:status => status
  4. end
  5.  
  6. def response_data
  7. status = options[:status] || 200
  8. message = options[:notice] || ''
  9. data = options[:data] || []
  10.  
  11. if data.blank? && !resource.blank?
  12. if has_errors?
  13. # Do whatever you need to your response to make this happen.
  14. # You'll generally just want to munge resource.errors here into the format you want.
  15. else
  16. # Do something here for other types of responses.
  17. end
  18. end
  19.  
  20. hash_for_json = { :data => data,:message => message }
  21.  
  22. [hash_for_json,status]
  23. end

猜你在找的Ruby相关文章