How to deal with not knowing what exceptions can be raised by a library method in Ruby?

大城市里の小女人 提交于 2019-12-03 04:45:59
theIV

(And yes I did look at the code of the library method, and can get some idea of what exceptions are raised but I cannot be 100% sure and if it is not documented I feel uncomfortable relying on it.)

I suggest having a look at the tests, as they will show some of the "likely" scenarios and what might be raised. Don't forget that good tests are documentation, too.

I guess that if no documentation is provided, you have to rely on something like this :

begin
   # code goes here
rescue
   # fail reason is in $!
end

Should you want to discard non valid JSON data:

begin
  res = JSON.parse(string)
rescue JSON::ParserError => e
  # string was not valid
end
Preet Sangha

You can never be sure what exceptions can be raised, unless the library code catches all and then wraps them. Your best bet is to assume good input from your code by sanitising what goes in and then use your own higher level exception handling to catch bad input from your inputs.

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