Catching a database exception in a model.save or model.save! method?
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 开发者_如何学Cit'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.
I wouldn't override the default behaviour of save, I would simple create my own method.
def save_with_exception_handler
begin
self.save!
rescue Exception => e
if e.is_a? ActiveRecord::StatementInvalid
# Do some processing and resave
end
end
end
Give it a better name that makes sense in your context, obviously. Then simply call where you are currently calling save:
model_instance.save_with_exception_handler
精彩评论