替代“救援例外”; [英] Alternative to "rescue Exception"
问题描述
我有时会遇到一些意外错误,例如超时错误,503错误等。有些错误我什至不知道可能会收到。我无法通过执行以下操作来考虑所有这些问题:
I get some unexpected errors on occasion such as timeout errors, 503 errors, etc. There are errors that I don't even know about that I may receive. I can't account for all of them by doing something like:
rescue Timeout::Error => e
挽救 Exception
。
我可以使用什么替代方法?我希望我的代码在出现错误时能够挽救所有代码;如果没有错误,则需要避免。我希望能够杀死我的脚本,但不能跳过语法错误等。
What is an alternative that I could use? I want my code to rescue all of them when there is an error; if there is no error, I need it to be avoided. I want to be able to kill my script but not skip over syntax errors, etc.
推荐答案
您可以为<$ c抢救$ c> StandardError ,或者只是抢救,它们是相同的:
You can rescue for StandardError
, or simply rescue, which are the same:
rescue StandardError => e
# or
rescue => e
您可以在下表中看到从 StandardError
-请注意,它们是 Exception
的子集,因此应该是可以捕获的错误。
You can see in the following table which exceptions are rescued from StandardError
- Note that they are a subset from Exception
, and conceitually should be errors that are OK to be catch.
当然,您可以在错误的位置使用宝石定义异常,但这在发达的宝石中不应发生。
Of course you can have gems that defines exception in the wrong place, but this should not happen in well-developed gems.
(来源: rubylearning.com )
我个人只想挽救我知道如何处理的异常,除非要添加在日志/回溯系统中查看以后的错误。如果是这种情况,我通常会抢救 StandardError
I personally like to rescue only exceptions I know how to handle, except when it is to add in a log/backtrace system to consult the errors later. If this is the case, I usually rescue StandardError
这篇关于替代“救援例外”;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!