2021-04-28 Rails action_dispatch.rescue_responses
action_dispatch.rescue_responses
config.action_dispatch.rescue_responses: HTTPステータスに割り当てる例外を設定します。ここには、例外とステータスのさまざまなペアを指定したハッシュを1つ指定可能です。デフォルトの定義は次のようになっています。
config.action_dispatch.rescue_responses = {
'ActionController::RoutingError' => :not_found,
'AbstractController::ActionNotFound' => :not_found,
'ActionController::MethodNotAllowed' => :method_not_allowed,
'ActionController::UnknownHttpMethod' => :method_not_allowed,
'ActionController::NotImplemented' => :not_implemented,
'ActionController::UnknownFormat' => :not_acceptable,
'ActionController::InvalidAuthenticityToken' => :unprocessable_entity,
'ActionController::InvalidCrossOriginRequest' => :unprocessable_entity,
'ActionDispatch::Http::Parameters::ParseError' => :bad_request,
'ActionController::BadRequest' => :bad_request,
'ActionController::ParameterMissing' => :bad_request,
'Rack::QueryParser::ParameterTypeError' => :bad_request,
'Rack::QueryParser::InvalidParameterError' => :bad_request,
'ActiveRecord::RecordNotFound' => :not_found,
'ActiveRecord::StaleObjectError' => :conflict,
'ActiveRecord::RecordInvalid' => :unprocessable_entity,
'ActiveRecord::RecordNotSaved' => :unprocessable_entity
}
実際にRails console で見てみるとこう。
> Rails.application.config.action_dispatch.rescue_responses
=> {"ActiveRecord::RecordNotFound"=>:not_found,
"ActiveRecord::StaleObjectError"=>:conflict,
"ActiveRecord::RecordInvalid"=>:unprocessable_entity,
"ActiveRecord::RecordNotSaved"=>:unprocessable_entity}
これにカスタムエラーを追加したい場合はこう。
Rails.application.config.action_dispatch.rescue_responses.update(MyCustomException => :not_found)