Check this commit for fix this pitfall (at least, as a Rubyist, i thought it should work), sure i eliminate the need of call exit
after this commit, but, i guess many user from Ruby thought original code should work.
Following is above code reduced version.
before commit,ensure not work when exit.
begin
chan = Channel(Tuple(String, String, Time::Span)).new
driver, capabilities = create_driver(browser, debug_mode)
begin
start_time = Time.monotonic
if engine_list.includes? Engine::Youdao
spawn Youdao.new(create_session(driver, capabilities), content, debug_mode, chan, start_time)
end
if engine_list.includes? Engine::Tencent
spawn Tencent.new(create_session(driver, capabilities), content, debug_mode, chan, start_time)
end
rescue e : Selenium::Error
e.inspect_with_backtrace(STDERR)
exit
end
DB.open DB_FILE do |db|
engine_list.size.times do
select
when result = chan.receive
# write DB
puts "Success"
when timeout timeout_seconds.seconds
STDERR.puts "Timeout!"
end
end
end
ensure
sleep 0.05
driver.stop if driver
end
Perhaps those code not good, need refactor, but, it should behavior correct.
when raise Selenium::Error, i want to skip write DB, but ensure stop driver.
new version (still not good, but behavior correct)
begin
chan = Channel(Tuple(String, String, Time::Span)).new
driver, capabilities = create_driver(browser, debug_mode)
start_time = Time.monotonic
if engine_list.includes? Engine::Youdao
spawn Youdao.new(create_session(driver, capabilities), content, debug_mode, chan, start_time)
end
if engine_list.includes? Engine::Tencent
spawn Tencent.new(create_session(driver, capabilities), content, debug_mode, chan, start_time)
end
DB.open DB_FILE do |db|
engine_list.size.times do
select
when result = chan.receive
# save db
puts "Success"
when timeout timeout_seconds.seconds
STDERR.puts "Timeout!"
end
end
end
rescue e : Selenium::Error
e.inspect_with_backtrace(STDERR)
ensure
sleep 0.05
driver.stop if driver
end
As you can see, i have to wrap the DB save logic into the begin/rescue block,
to ensure driver always stop when raise Selenium::Error, but that really not necessary,
we should always make the begin/rescue
block as small as possible
(only include the code which can raise Selenium::Error), right?
I don’t know if this is a good example, anyway, this is a issue i meet when i coding.