Skip to content

Instantly share code, notes, and snippets.

@zerebubuth
Created November 28, 2016 02:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zerebubuth/8211e07e9f592e5b8146dea2344906b7 to your computer and use it in GitHub Desktop.
Save zerebubuth/8211e07e9f592e5b8146dea2344906b7 to your computer and use it in GitHub Desktop.
Trying to figure out why timeout errors cause commits
require 'timeout'
# loosely based on https://github.com/rails/rails/blob/v4.2.7.1/activerecord/lib/active_record/connection_adapters/abstract/transaction.rb#L182-L201
def transaction
yield
rescue Exception => error
STDERR.puts "Rescued exception: #{error.to_s}"
raise
ensure
STDERR.puts "Ensuring..."
unless error
status = Thread.current.status
STDERR.puts "Error was falsey, trying to commit transaction! (current thread status #{status.inspect})"
end
end
class CustomTimeoutError < RuntimeError
def to_s
"Custom Timeout Error"
end
end
# loosely based on openstreetmap-website/app/controller/application_controller.rb:345
def api_call_timeout(custom_error = nil)
Timeout.timeout(1, custom_error) do
yield
end
rescue Timeout::Error
STDERR.puts "Rescued API call timeout."
raise CustomTimeoutError
end
# when transaction wraps timeout, all is okay:
STDERR.puts "transaction { api_call_timeout { ... } }"
begin
transaction { api_call_timeout { sleep 2 } }
rescue Exception => e
STDERR.puts "Top level rescue: #{e.to_s}"
end
STDERR.puts
# when timeout wraps transaction, it attempts to commit the transaction
STDERR.puts "api_call_timeout { transaction { ... } }"
begin
api_call_timeout { transaction { sleep 2 } }
rescue Exception => e
STDERR.puts "Top level rescue: #{e.to_s}"
end
STDERR.puts
# Fix is to use Timeout.timeout to inject a custom exception?
STDERR.puts "api_call_timeout(CustomTimeoutError) { transaction { ... } }"
begin
api_call_timeout(CustomTimeoutError) { transaction { sleep 2 } }
rescue Exception => e
STDERR.puts "Top level rescue: #{e.to_s}"
end
STDERR.puts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment