简体   繁体   English

在ruby中的“ raise”语句之后,如何使脚本继续运行?

[英]How to make script continues to run after 'raise' statement in ruby?

I'm checking to see if there is any error message in a log file. 我正在检查日志文件中是否有任何错误消息。 If an error message found in a log file, then I use 'raise' statement to report the founding. 如果在日志文件中发现错误消息,那么我将使用“ raise”语句来报告创建情况。 However ruby stops running after executed the 'raise' statement, even when I use 'rescue'. 但是,即使执行了“ rescue”,ruby在执行“ raise”语句后也会停止运行。 I'd like script continue checking next log file for error after the 'raise' statement, but not sure how. 我希望脚本在“ raise”语句之后继续检查下一个日志文件是否有错误,但不确定如何。 Any help would be appreciated! 任何帮助,将不胜感激!

        logs_all = s.sudo "egrep -i '#{error_message}' #{log_file}"
        logs_all.each do |hostname, logs|
           unless logs.empty?
            puts line, "Unhappy logs on #{hostname}", line, logs
            happy = false
           end

           begin

            raise "Unhappy logs found! in #{log_file}" unless happy

           rescue raise => error
            puts error.message
           end


        end

Your rescue statement doesn't look right: 您的救援声明看起来不正确:

rescue raise => error

should be: 应该:

rescue => error

which is equivalent to: 等效于:

rescue StandardError => error

If you rescue an exception and don't re-raise it, ruby will continue on. 如果您抢救了异常并且不重新提出它,那么红宝石将继续存在。 You can easily verify this with something like: 您可以使用以下类似方法轻松地验证这一点:

3.times do |i|
  begin
    raise "Raised from iteration #{i}"
  rescue => e
    puts e
  end
end

You'll see that three lines of output are printed. 您将看到打印了三行输出。

As a general practice though, you should avoid rescuing Exceptions unless you're going to do something at runtime to rectify the problem. 不过,作为一般惯例,除非要在运行时执行某些操作来纠正问题,否则应避免挽救Exception。 Rescuing and not re-throwing exceptions can hide problems in your code. 抢救而不是不抛出异常会在代码中隐藏问题。

And more generally, please follow Sergio's advice above and don't use exceptions as control flow. 更一般地说,请遵循以上 Sergio的建议 ,不要将异常用作控制流。

Further Reading 进一步阅读

You are using exceptions as control flow mechanism. 您正在使用异常作为控制流机制。 Don't. 别。

What is it that you want to do with unhappy logs? 您想对不满意的日志做什么? Print them? 打印吗? To a file, maybe? 要归档吗? Do that, don't raise exceptions. 做到这一点,不要引发例外。

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

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