0

我有以下内容:

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

我在这里遇到的问题是,在我的恢复中,我需要访问开始块中的几个变量,所以当我调用 RAISE 时我试图传递它们。这似乎不起作用。此外,这些变量在许多加注中是一致的,因此它确实填满了页面。

有没有办法让这些变量在resuce中访问而不必在raise中定义它们?

如果没有,我如何使用 raise 将它们传递给救援?上述错误与:

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
                                 ^

谢谢!

4

1 回答 1

1

rescue关键字只是捕获错误对象。您需要在异常对象中捕获这些值:

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

但是这是对错误处理的滥用。通常最好使用 begin 和 raise 来处理真正的错误,即您没有预料到的错误。MissingInfo 听起来像是处理用户输入。您可以预期用户输入会丢失数据。对此进行常规检查。试着想想你真正想要传达的行为。

于 2010-12-12T21:26:15.980 回答