0
我有一個一般的rails問題,儘管有大量的搜索,但我還是沒有找到答案。 對於json rest apis,處理運行時異常(意外錯誤)的建議方法是什麼?在更新操作上使用respond_with時遇到一些問題。我不得不回退到respond_to。例如,這是一個很好的模式?有更好的選擇嗎?另外,其他應用程序採用何種方法來覆蓋所有操作,以便以正確的格式將響應發送回客戶端(html用於html請求,json用於應用程序/ json請求)?使用respond_with更新的json請求的Rails異常處理
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