简体   繁体   English

在更新时使用response_with对JSON请求进行Rails异常处理

[英]Rails exception handling for json requests using respond_with on update

I have a general rails question for which I didn't not find an answer despite good amount of searching around. 我有一个通用的Rails问题,尽管经过大量搜索,但没有找到答案。 What is the recommended approach to handling exceptions arising at runtime (unexpected errors) for json rest apis ? 建议的处理json rest api的运行时异常(意外错误)的推荐方法是什么 I am having some trouble using respond_with on update actions. 我在更新操作上使用response_with遇到了一些麻烦。 I am having to fallback to respond_to. 我必须回退到response_to。 For example, is this a good pattern? 例如,这是一个好模式吗? Is there a better alternative? 有更好的选择吗? Also, what is the approach other applications take to blanket ALL actions so responses are sent back to the client in the right format (html for html requests and json for application/json requests) ? 另外, 其他应用程序采用什么方法来覆盖所有操作,以便以正确的格式(对于html请求为html,对于应用程序/ json请求为json)将响应发送回客户端

def update
  begin
     User.update_attributes(params[:user]))
     #assume some other logic here raises an exception (a runtime unexpected error)
  rescue => ex
      errors = {}
      errors['errors'] = [] << ex.message
     #not having this rescue here will cause rails to respond with a html error page 
     #which is not what the client is looking for (client expects json responses)
     #however, if I rescue any runtime errors, I have a chance to respond 
     #in the way the client expects. Also, respond_with here won't work 
     #because I am getting a 204 response back. So I am forced to use respond_to in the ugly way
    respond_to do |format|
        format.html # some.html.erb
        format.json  { render :json => errors.to_json, :status=>400 }
      end
  end
end

try this 尝试这个

respond_to do |format|
  ...
  format.json { render :json => ex.message, :status => 400 }
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM