3

I am saving data to a table.

Question
  title:string
  author_id:integer
  description:text
  upvotes:integer

If a "question.upvotes" value is 1000000000000000000000, it will cause an error since it can't be saved to the "integer" type column.

How can I suppress this error? I want my program to continue running, even though the record failed to save.

I tried this, but it doesn't suppress the error:

... some code

if my_question.save
end

some more code...
Don P
  • 60,113
  • 114
  • 300
  • 432
  • What error does it cause? What do you see when it fails to update? – Niels Abildgaard Dec 31 '14 at 09:42
  • Have you looked at the [documentation for `save`](http://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-save)? – Niels Abildgaard Dec 31 '14 at 09:45
  • @NielsAbildgaard this is likely a general Ruby question dealing with try / catch syntax, not specific to the active record .save method – Don P Dec 31 '14 at 09:47
  • error is `PG::NumericValueOutOfRange: ERROR: value "1000000000000" is out of range for type integer` – Don P Dec 31 '14 at 09:48
  • Or you could just test the value to see if it won't save. That said, silently failing to meet the user expectation and perhaps an other programmer's is a not a good general design principle. – Tony Hopkinson Dec 31 '14 at 09:53
  • @Donny P the error does not arise when saving. It happens before that: when you try to pass a non-integer number (too large) as an argument to a function which takes an integer. Validation before trying to save is the best solution. – Niels Abildgaard Dec 31 '14 at 10:00

2 Answers2

2

Perhaps just pin that value to the biggest possible value? Add something like this to your Question model:

# app/models/question.rb
UPVOTE_MAX_VALUE = 2_147_483_647          # integer max value in postgresql
before_validation :check_upvote_max_size

private
def check_upvotes_max_size
  self.upvotes = UPVOTE_MAX_VALUE         if upvotes > UPVOTE_MAX_VALUE
end
spickermann
  • 100,941
  • 9
  • 101
  • 131
1
... some code

begin
  if my_question.save
    ...
  end
rescue
  # error handling
end

some more code ...

You receive ActiveRecord::StatementInvalid: PG::NumericValueOutOfRange: ERROR: integer out of range error. If you want to catch exactly this error, you can specify this directly:

rescue ActiveRecord::StatementInvalid

also you can add a block which will be always executed with

ensure

You can find more about exceptions handling here / And see exceptions hierarchy here

Community
  • 1
  • 1
Rustam Gasanov
  • 15,290
  • 8
  • 59
  • 72
  • In Rails 5.2 `ActiveModel::RangeError` is raised instead. Man this makes things rescue logic brittle. – lulalala Jan 15 '18 at 15:41