Ankit Singhaniya Ankit Singhaniya - 12 days ago 7
Ruby Question

How to rescue PG::NotNullViolation error in Ruby?

I am getting

ActiveRecord::StatementInvalid: PG::NotNullViolation: ERROR
. Can anyone tell me how can I rescue the
PG::NotNullViolation
?

begin
x.save
rescue ActiveRecord::StatementInvalid
puts "I get here"
end


But I want to rescue the exact error, do we have a way to do it?

Answer

You can do it with regexp an error's message

begin
 x.save 
rescue ActiveRecord::StatementInvalid => e
  if e.message =~ /^PG::NotNullViolation/
    puts 'Error!!!'
  end
end