0
votes

Does anyone know how to rescue this ActiveRecord::StatementInvalid error in rails? The console displays "PG::InvalidTextRepresentation: ERROR: invalid input syntax for integer...". I've tried inserting a pry into the rescue block, but it's never called.

  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

Please note that I know how to prevent the error from occurring (i.e. need to convert the key to type integer for the id columns). But, I'm trying to understand why it never reaches the rescue block.

UPDATE: my initial post contained a syntax error (namely: rescue e => error) as others correctly pointed out. i'm still receiving the same error without the syntax error; i've update the code to remove the incorrect syntax.

2
rescue e => error should just be rescue ActiveRecord::StatementInvalid => errorengineersmnky
@lgants did you ever figure out what was wrong here?Daniel Kotin

2 Answers

4
votes

This isn't the correct syntax for rescue:

rescue e => error

if I try and use this I get undefined local variable or method 'e'

The standard way to rescue a specific error class is to use:

rescue ActiveRecord::StatementInvalid => e

To do a "naked rescue" (which is often advised against), leave out the class name:

rescue => e

Note that in all these cases the => e can be left out if you don't need a variable pointing to the error object.

0
votes

rescue ActiveRecord::StatementInvalid => e is the right syntax and should work fine, but also keep in mind that exception should actually be raised within that block.

rails executes a query when we actually try using its output(for example rendering page where we are displaying output of a query).