I am trying to make my code more robust by adding begin/rescue blocks
around my *.find calls in my methods. Unfortunately, I do not seem to
be able to accomplish what I am hoping to do. Here is an example of my
attempt:
def getProductNames()
productNames = Array.new
begin
Product.find(:all).each do |product|
productNames.push(product.name)
end
rescue
end
productNames
end
When shutting down my database and calling this method, no error is
logged and the caller fails with a database connection error, which I am
trying to catch with my rescue block above. I am hoping to log the
error but simply return the empty array to the caller so life can go
on… Is Rails discovering this error and responding before my method
is ever invoked? When I open a console and execute the same thing, my
rescue code is executed-- why is it not executed here?
You’ve got an interesting question here. My guess is that you’re
shutting down the database well prior to execution of the above method.
Most likely before any model code is executed. I believe at the time
a model is read via the ruby engine (not necessarily executed) it will
connect to the database and it’s failing at that point. I hope that
made sense.
I’m interested as well in a more detailed answer to this question. But
for starters, I believe that’s what you’re looking at. You may wish to
use a more global rescue block to catch the exception occuring early in
the process. You should be able to display some diagnostic info from
there.
Thanks for the response… I am rather new to the RoR framework, etc.,
so I am not exactly sure where I could catch the exception earlier.
Would that be in some system code? I should mention that my methods are
all individual methods that are called via a web service, and therefore
act “alone”-- i.e. there is no larger application on my end to catch a
database exception.
Generally speaking, however, I would think that this problem exists for anyone attempting to handle an inaccessible database in Ruby/Rails, so
someone must know how to do this… right?
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.