简体   繁体   English

开始救援没有捕获错误

[英]Begin Rescue not catching error

I'm using some ruby code wrapped in a begin - rescue block but somehow it manages to still crash. 我正在使用一些包含在开始 - 救援块中的红宝石代码,但不知怎的,它设法仍然崩溃。

the block of code looks like this: 代码块看起来像这样:

# Retrieve messages from server
def get_messages
  @connection.select('INBOX')
  @connection.uid_search(['ALL']).each do |uid|
    msg = @connection.uid_fetch(uid,'RFC822').first.attr['RFC822']
    begin
      process_message(msg)
      add_to_processed_folder(uid) if @processed_folder
    rescue
       handle_bogus_message(msg)
    end
    # Mark message as deleted 
    @connection.uid_store(uid, "+FLAGS", [:Seen, :Deleted])
  end
end

Given this code i would assume that if process_message or add_to_processed_folder could not execute then rescue would kick in and call handle_bogus_message . 鉴于此代码,我假设如果process_messageadd_to_processed_folder无法执行,那么rescue将启动并调用handle_bogus_message That being said I'm running this code in a production environment and sometimes when i "get" an email message (this is run from a rake task) it dies with a SyntaxError . 话虽这么说,我在生产环境中运行此代码,有时当我“获取”电子邮件消息(这是从rake任务运行)时,它会死于SyntaxError

For a look at the error message check out http://pastie.org/1028479 and not that process_message that it is referring to is the same process_message above. 一看错误消息退房http://pastie.org/1028479并不算process_message,它指的是上述相同process_message。 Is there any reason why begin - rescue won't catch this exception? 是否有任何理由为什么开始 - 救援不会抓住这个例外?

rescue without a parameter just rescues exceptions that inherit from StandardError . rescue不带参数只是抢救,从继承异常StandardError To rescue a SyntaxError use rescue SyntaxError . 要解救SyntaxError使用rescue SyntaxError

To rescue all exceptions you would use rescue Exception , but note that that's a bad idea (which is why it's not the default behavior of rescue ) as explained here and here . 为了拯救所有异常你将使用rescue Exception ,但请注意,这是一个坏主意(这就是为什么它不是rescue的默认行为),如此此处所述 Especially this part: 特别是这部分:

Rescuing Interrupt prevents the user from using CTRLC to exit the program. Rescuing Interrupt阻止用户使用CTRLC退出程序。

Rescuing SignalException prevents the program from responding correctly to signals. 抢救SignalException会阻止程序正确响应信号。 It will be unkillable except by kill -9. 除了kill -9之外它将是不可杀死的。

rescue without any parameter accepts exceptions raised by StandardError class. 不带任何参数的rescue接受StandardError类引发的异常。 Your error type is SyntaxError which is inherited from a different class called ScriptError. 您的错误类型是SyntaxError,它继承自名为ScriptError的其他类。 All these error classes are subclasses of Exception class. 所有这些错误类都是Exception类的子类。 So as sepp2k suggested use rescue Exception to catch all kinds of exceptions. 因此sepp2k建议使用rescue Exception来捕获各种异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM