0

我有一个一般性的 rails 问题,尽管进行了大量搜索,但我没有找到答案。为 json rest apis 处理运行时出现的异常(意外错误)的推荐方法是什么?我在更新操作上使用 respond_with 时遇到了一些问题。我不得不回退到respond_to。例如,这是一个好的模式吗?有更好的选择吗?此外,其他应用程序采取什么方法来覆盖所有操作,以便以正确的格式(html 用于 html 请求,json 用于 application/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
4

1 回答 1

0

尝试这个

respond_to do |format|
  ...
  format.json { render :json => ex.message, :status => 400 }
end
于 2012-11-24T06:55:49.757 回答