Reputation: 1591
I have a ruby app that uses ActiveRecord
but not Rails
.
I want to rescue from all database errors which in my case can include a SQLite3::BusyException
.
Is there a better way than to wrap every Model.find
, Model.where
, obj.save
, etc in a rescue?
I thought adding a module to every model that monkey patches/hijacks DB actions such as, but where
appears complex and something not to be trifled with:
def where
super
rescue ActiveRecord::RecordNotFound
rescue SQLite3::BusyException => e
p [:warning, e.message]
end
Upvotes: 0
Views: 214
Reputation: 84
When using Celluloid I ran into a similar issue where I needed to trap errors due to the connection pooling not working correctly with how Celluloid was using fibers. I used something like the following wrapper method to help make sure errors were trapped and resolved the connection reaping in my code. For your scenario, it could look like this:
module TrackActiveRecordErrors
def db(&block)
begin
yield block
rescue StandardError => e
p [:warning, e.message]
# ... and other sort of logging, alerting you'd like
raise e
ensure
# Put your clean-up code here
end
end
end
In classes you want to use this wrapper:
class DoSomething
include TrackActiveRecordErrors
def find_something(id)
db do
a_something = Model.find(id)
end
a_something
end
end
It's not pretty, but it's a lot easier than trying to tune AR's magic in the model classes.
Upvotes: 1