How do I pass an error from my Module back to the rake task that called it?
My rake task looks like this:
require 'mymodule.rb'
task :queue => :environment do
OPERATOR = Mymodule::Operator.new
begin
OPERATOR.initiate_call (1234567189)
rescue StandardError => bang
puts "Shit happened: #{ bang} "
end
end
And here is my module..
module Mymodule
class Operator
def initiate_call (number)
begin
# make the call
rescue StandardError => bang
flash[:error] = "Error #{bang}"
return
end
end
end
end
I also call this module from a controller so it would be nice to have an error handling solution that is more or less agnostic.
Running Rails 3. Any unrelated comments (i.e. suggestions) on my code structure are more than welcomed 🙂
Your
Operator#initiate_callmethod trapsStandardErrorexceptions so your rake task will never see them. I’d drop therescuefrominitiate_calland let the caller deal with all the exception handling. Then, you’d haveflash[:error] = "Error #{bang}"in your controller’s exception handler and the rake task would remain as-is.The basic approach is to push the error handling up the call stack all the way to someone that can do something about it;
initiate_callcan’t really do anything useful with the exception so it shouldn’t try to handle it.