Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何在rescue中捕获参数转换错误_Ruby_Ruby On Rails 4 - Fatal编程技术网

Ruby 如何在rescue中捕获参数转换错误

Ruby 如何在rescue中捕获参数转换错误,ruby,ruby-on-rails-4,Ruby,Ruby On Rails 4,我正在学习ruby并在做一些事情。我有controller.rb def city params.require(:id) begin @data = @user.city_details(Integer(params[:id]), params[:city_name] rescue ArgumentError => e render_error(:bad_request, e.message) e

我正在学习ruby并在做一些事情。我有controller.rb

def city
  params.require(:id)
  begin
    @data = @user.city_details(Integer(params[:id]),
                              params[:city_name]
  rescue ArgumentError => e
    render_error(:bad_request, e.message)
  end
end
model.rb

  def city_details(id, city_name = 'philly')
    StoredProcedure::User::GetCityDetails.exec!(
        id,
        city_name
    )
  end
end

如何更新控制器以仅捕获与参数id转换相关的错误,而不捕获任何与模型相关的错误?

我将在模型方法之前强制转换参数,以确保捕获正确的内容:

id = begin
  Integer(params[:id])
rescue ArgumentError => e
  render_error(:bad_request, e.message)
end
@data = @user.city_details(id)
您还可以在控制器的顶层添加rescue

class MyController

  rescue_from ArgumentError do
    // code here
  end

  def mymethod
    id = Integer(params[:id])
  end
end

补充卡尔的答案,也可以是:

id = Integer(params[:id]) rescue render_error(:bad_request, 'Invalid id')