Suppressing error while saving record in Rails
I am storing data in a table.
Question
title:string
author_id:integer
description:text
upvotes:integer
If the value "question.upvotes" is 1000000000000000000000, this will result in an error because it cannot be stored in an integer column.
How can I suppress this error? I want my program to keep running even though the record could not be saved.
I tried this, but it doesn't suppress the error:
... some code
if my_question.save
end
some more code...
source to share
... some code
begin
if my_question.save
...
end
rescue
# error handling
end
some more code ...
You are getting an error ActiveRecord::StatementInvalid: PG::NumericValueOutOfRange: ERROR: integer out of range
. If you want to pinpoint this error, you can specify it directly:
rescue ActiveRecord::StatementInvalid
also you can add a block that will always execute with
ensure
You can find more details about exception handling here / And look here for the exception hierarchy
source to share
Perhaps just bind this value to the largest possible value? Add something like this model Question
:
# 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
source to share