Ruby Timeout::timeout doesn't fire Exception and doesn't return what documented

别来无恙 提交于 2019-12-03 12:01:21

Your code is correct

require 'timeout'
begin
  complete_results = Timeout.timeout(1) do      
   sleep(2)
  end
rescue Timeout::Error
  puts 'Print me something please'
end

does print out "print me something please".

Try the basic code as above. If that works, you have an issue in platform.search.

The problem is that platform.search is catching the exception that Timeout#timeout throws.

You can get around this by wrapping your inner code in another thread -- YMMV.

begin
  complete_results = Timeout.timeout(4) do
    Thread.new{ results = platform.search(artist, album_name) }.value
  end
rescue Timeout::Error
  puts 'Print me something please'
end 

According to the documentation:

If the block execution terminates before sec seconds has passed, it returns true. If not, it terminates the execution and raises exception (which defaults to Timeout::Error)

This means it only returns true if it's successful, otherwise the variable will not be set (ie it's nil NOT false).

As far as your example goes, it's definitely timing out for me and getting to the rescue part...

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