Hello,
I have two models that when saving certain types of data, it causes the database to throw an exception. I can convert the data before saving to avoid the exception, but the conversion is expensive and the exception happens very rarely.
So, I was wondering if it's possible to create an override of the model.save method, and catch an exception that's thrown from the database? Would that work?
For example:
def save
begin
super
rescue Exception => e
if e.is_a? ActiveRecord::StatementInvalid
# Do some processing and resave
end
end
end
The reason why I'd like to do this is because I've already had to repeat a big chunk of handling code between the two models that have this problem, and also because I'd like to avoid the potential issue of calling save elsewhere later, but not adding in the exception handling code.
For instance, when writing some test code and calling save directly, the error data threw an exception.
So, a few questions:
- Is it even possible to catch an exception from within a save or save! method?
- After fixing the data, how do I attempt to save again? Do I just call super() again?
- Is there a better way of handling this?
Thank you very much.