如何挽救 ActiveRecord::StatementInvalid 错误

lga*_*nts 0 ruby postgresql activerecord ruby-on-rails

有谁知道如何挽救 Rails 中的 ActiveRecord::StatementInvalid 错误?控制台显示“PG::InvalidTextRepresentation: 错误: 整数的输入语法无效...”。我尝试过将撬片插入救援块,但从未被调用。

  if (resource_params[:term].present?)
    begin
      key = resource_params[:term]
      scope = scope.where("id = ? OR item_type = ? OR item_id = ? OR event = ? OR object ILIKE ?", key, key, key, key, "%#{key}%") 
    rescue
      # handle error 
    end 
  end
Run Code Online (Sandbox Code Playgroud)

请注意,我知道如何防止错误发生(即需要将键转换为 id 列的整数类型)。但是,我试图理解为什么它永远不会到达救援区。

更新:我最初的帖子包含一个语法错误(即:rescue e => error),正如其他人正确指出的那样。我仍然收到相同的错误,但没有语法错误;我已经更新了代码以删除不正确的语法。

max*_*ner 5

这不是救援的正确语法:

rescue e => error
Run Code Online (Sandbox Code Playgroud)

如果我尝试使用这个我会得到undefined local variable or method 'e'

挽救特定错误类的标准方法是使用:

rescue ActiveRecord::StatementInvalid => e
Run Code Online (Sandbox Code Playgroud)

要进行“裸体救援”(通常建议不要这样做),请省略类名称:

rescue => e
Run Code Online (Sandbox Code Playgroud)

请注意,在所有这些情况下,=> e如果不需要指向错误对象的变量,则可以省略。