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

时间:2012-11-24 06:51:07

标签: ruby-on-rails json respond-with

我有一个普通的铁轨问题,尽管有大量的搜索,我仍然没有找到答案。 为json rest apis 处理运行时出现的异常(意外错误)的推荐方法是什么?我在使用respond_with更新操作时遇到了一些麻烦。我不得不回应response_to。例如,这是一个好的模式吗?还有更好的选择吗?此外,其他应用程序采取什么方法来覆盖所有操作,以便以正确的格式将响应发送回客户端(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

1 个答案:

答案 0 :(得分:0)

试试这个

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