0

デフォルトでは、Railsは404 Resource Not Found500 Internal Server Errorの役に立つHTMLページを提供します。しかし、私のJSON APIでは、JSON形式の返信を提供したいと思います。Rails 3のデフォルト例外+ JSONリクエストの処理404

JSONリクエストのデフォルトの例外処理を設定するにはどうすればよいですか?

答えて

0

私は、すべてのAPIコントローラのベースコントローラを追加しました:

NOT_FOUND_EXC = [ActionController::RoutingError, 
       AbstractController::ActionNotFound, 
       ActiveRecord::RecordNotFound] 

class BaseapiController < ActionController::Base 
    respond_to :json 
    rescue_from StandardError, with: :show_json_error 

    def resource_not_found 
    url = request.fullpath 
    respond_with(url), status: :not_found) 
    end 

    private 

    def show_json_errors(exc) 
    case exc 
     when *NOT_FOUND_EXC 
     return resource_not_found 
     else 
     logger.error exc.message 
     logger.error exc.backtrace.join("\n") 
     respond_with(exc), status: :internal_server_error) 
    end 
    end 
end 

を私はroutes.rbでこれを定義した:

namespace :api do 
    ... 
end 
match 'api/*url', to: 'baseapi#resource_not_found' 

rescue_from句は、すべての例外と比類のないルートをキャプチャします#resource_not_foundによってキャプチャされます。

これは、通常、エラーは開発時に表現力豊かな詳細で処理され、単純にprodでレンダリングされるため、Railsの例外処理に関するいくつかの基本的なことを忘れていると思います。私は明らかにここでそれをやっていません。 HTMLの例外はまだ漏れている可能性があります。フィードバックや代替案が大歓迎です。私はRailsには初心者です。