0

一般的なレールの質問がありますが、かなりの量を検索しても答えが見つかりませんでした。json rest api の実行時に発生する例外 (予期しないエラー) を処理するための推奨されるアプローチは何ですか? 更新アクションで Respond_with を使用すると問題が発生します。Respond_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
4

1 に答える 1

0

これを試して

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