0
我正在使用一個在後臺線程中拋出異常的gem,如下所示。我想趕上這個例外,但不知道如何去做。如何去處理庫線程中的異常?Ruby,捕獲庫線程異常?
#this class is in my code
class MQTT
def self.connect
@client = Client.connect(options)
end
ende
這個類是被包裝作爲寶石庫,所以我在技術上沒有訪問到它:
class Client
def self.connect(*args, &block)
client = Client.new(*args)
client.connect(&block)
return client
end
def connect(clientid=nil)
# Start packet reading thread
@read_thread = Thread.new(Thread.current) do |parent|
Thread.current[:parent] = parent
loop { receive_packet }
end
end
def receive_packet
begin
# Poll socket - is there data waiting?
result = IO.select([@socket], nil, nil, SELECT_TIMEOUT)
# Pass exceptions up to parent thread
rescue Exception => exp
unless @socket.nil?
@socket.close
@socket = nil
end
Thread.current[:parent].raise(exp)
end
end
end
謝謝!所有這些解決方案都很有用,但啓動新線程的代碼位於gem內。我可以在不修改庫源的情況下使用其中的任何一種嗎? – WindsurferOak