ruby – 像Github api v3一样为Rails 3定制Api错误
发布时间:2020-12-17 04:37:29 所属栏目:百科 来源:网络整理
导读:我在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": "
我在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" } ] } 我喜欢错误消息结构.但无法让它重现. 解决方法
您可以通过为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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
热点阅读