Reputation: 168101
How can I capture an exception from another thread?
abort_on_exception
to true
.puts
, pp
, etc. with the exception within the thread that raised in exception.I found an answer in How to get error messages from ruby threads that suggests using catch
, and I think that is the way I want to go, but I cannot not fully figure out how to do it. Or is there a better way? I also found an answer suggesting to use Queue
class, but have concern that it may be overkill.
Upvotes: 2
Views: 204
Reputation: 211580
If you turn on abort_on_exception
then you won't have a chance to catch it. You can, however, leave that off and simply catch it when you do the join
operation on your thread.
thread = Thread.new do
raise "Uh oh"
end
begin
thread.join
rescue => e
puts "Caught exception: #{e}"
end
The alternative is to make the thread catch its own exception and save it somewhere you can fetch it from later. For instance:
exceptions = { }
Thread.new do
begin
raise "Uh oh"
rescue => e
exceptions[Thread.current] = e
end
end
sleep(1)
puts exceptions.inspect
# => {#<Thread:0x007f9832889920 dead>=>#<RuntimeError: Uh oh>}
Upvotes: 2