开始救援未捕获错误
我正在使用一些包含在 begin -rescue 块中的 ruby 代码,但不知何故它仍然崩溃。
代码块如下所示:
# 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
鉴于此代码,我假设如果 process_message 或 add_to_processed_folder 无法执行,则救援将启动并调用 handle_bogus_message >。话虽这么说,我在生产环境中运行此代码,有时当我“收到”电子邮件消息(这是从 rake 任务运行)时,它会因SyntaxError而终止。
要查看错误消息,请查看 http://pastie.org/1028479,而不是 process_message它所指的与上面的process_message相同。有什么原因导致 begin - rescue 不会捕获此异常?
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. 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.
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. Is there any reason why begin - rescue won't catch this exception?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不带任何参数的
rescue
接受 StandardError 类引发的异常。您的错误类型是 SyntaxError,它继承自另一个名为 ScriptError 的类。所有这些错误类都是 Exception 类的子类。因此,正如 sepp2k 建议的那样,使用rescue Exception
来捕获各种异常。rescue
without any parameter accepts exceptions raised by StandardError class. Your error type is SyntaxError which is inherited from a different class called ScriptError. All these error classes are subclasses of Exception class. So as sepp2k suggested userescue Exception
to catch all kinds of exceptions.不带参数的
rescue
仅挽救从StandardError
继承的异常。要挽救SyntaxError
,请使用rescue SyntaxError
。要拯救所有异常,您可以使用
rescue Exception
,但请注意,这是一个坏主意(这就是为什么它不是rescue
的默认行为),如 此处 和此处。尤其是这一部分:rescue
without a parameter just rescues exceptions that inherit fromStandardError
. To rescue aSyntaxError
userescue 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 ofrescue
) as explained here and here. Especially this part: