I have the following:
class MailingJob < Struct.new(:mailing_id)
class MissingInfo < ArgumentError; end
def perform
....
begin
......
raise MissingInfo, "Not found", message_all, @message_from if @message_reply.length == 0
......
rescue MissingInfo => reason, message_all, message_from
UserMailer.delay.incoming_mails_error_notification(reason, message_all, message_from)
end
end
The problem I'm having here is that in my resuce, I need access t开发者_开发百科o several of the vars in the begin block, so I'm trying to pass them when I call RAISE. That doesn't appear to be working. Also, these variables are consisten across many raises, so it really fills up the page.
Is there a way to make these variable accessible in the resuce without having to define them in the raise?
If not, how do I use raise to pass them to the rescue? The above errors with:
SyntaxError (/Users/xxxxx/Sites/xxxxxxx/lib/mailing_job.rb:117: syntax error, unexpected ',', expecting kTHEN or ':' or '\n' or ';'
rescue MissingInfo => reason, message_all, message_from
^
Thank you!
The rescue
keyword just captures the error object. You need to capture these values inside an exception object:
class MissingInfo < ArgumentError
attr_accessor :messages
def initialize(messages = {})
self.messages = messages
end
end
begin
raise MissingInfo.new(:all => message_all, :from => message_from, :reason => reason)
rescue MissingInfo => missing_info
puts missing_info.messages[:all]
end
BUT This is an abuse of error handling. It's usually better to use begin and raise for real errors, errors which you do not expect. MissingInfo sounds like handling user input. You can expect user input to have missing data. Do normal checks for that. Try to think of the behavior you are really trying to convey.
精彩评论