Alternative to “rescue Exception”

陌路散爱 提交于 2019-12-13 01:13:13

问题


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

It's also a terrible idea to rescue 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.


回答1:


You can rescue for StandardError, or simply rescue, which are the same:

rescue StandardError => e
# or
rescue => e

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.


(source: rubylearning.com)

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



来源:https://stackoverflow.com/questions/18596785/alternative-to-rescue-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!