Skip to content

Instantly share code, notes, and snippets.

@larskanis
Last active June 20, 2022 13:36
Show Gist options
  • Save larskanis/8b47828d6740f031de72 to your computer and use it in GitHub Desktop.
Save larskanis/8b47828d6740f031de72 to your computer and use it in GitHub Desktop.
Monkey patch PG::Connection to get more a descriptive error message
require 'pg'
class PG::Connection
def self.wrap_send_method(meth)
alias_method "#{meth}_wo_wrap", meth
define_method(meth) do |*args|
begin
send("#{meth}_wo_wrap", *args)
rescue PG::UnableToSend => e
raise e, "#{e} previous command was #{@last_cmd.inspect}"
end
@last_cmd = [meth, args, caller]
end
end
def self.wrap_send_methods(*args)
args.each { |meth| wrap_send_method(meth) }
end
wrap_send_methods :send_query, :send_prepare, :send_query_prepared,
:send_describe_prepared, :send_describe_portal,
:exec, :exec_params, :exec_prepared, :async_exec, :query,
:prepare, :describe_prepared
end
if $0 == __FILE__
conn = PGconn.new
conn.send_query("select 1")
conn.send_query("select 2")
# $ ruby pg_log_unable_to_send.rb
# pg_log_unable_to_send.rb:11:in `rescue in block in wrap_send_method': another command is already in progress (PG::UnableToSend)
# previous command was [:send_query, ["select 1"], ["pg_log_unable_to_send.rb:29:in `<main>'"]]
# from pg_log_unable_to_send.rb:8:in `block in wrap_send_method'
# from pg_log_unable_to_send.rb:30:in `<main>'
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment