Skip to content

Instantly share code, notes, and snippets.

@hoverlover
Last active November 26, 2019 08:57
Show Gist options
  • Save hoverlover/a16ff56c8f7617da7db9 to your computer and use it in GitHub Desktop.
Save hoverlover/a16ff56c8f7617da7db9 to your computer and use it in GitHub Desktop.
PG::LockNotAvailable rescue woes
def save_with_lock
r = Record.first
# This will raise PG::LockNotAvailable if already locked
#
r.with_lock("FOR UPDATE NOWAIT") do
# do stuff
end
# This rescue block isn't executed for some reason??
#
rescue PG::LockNotAvailable
puts "lock not available"
# But this one works
#
rescue ActiveRecord::StatementInvalid => e
if e.message.include? "LockNotAvailable"
puts "lock not available"
else
raise
end
end
@ktravers
Copy link

@hoverlover hi there! thanks for posting this workaround. i'm experiencing the same woes in one of my rails projects. just curious - did you ever find out why PG::LockNotAvailable doesn't get rescued here?

@sethsweepnovu
Copy link

rescue ActiveRecord::StatementInvalid => exception
        raise exception unless exception.cause.is_a? PG::LockNotAvailable

@BuonOmo
Copy link

BuonOmo commented Nov 26, 2019

@sethsweepnovu I've always wondering, why not just using rescue ActiveRecord::LockWaitTimeout without care about the bubbled error?

@ktravers

did you ever find out why PG::LockNotAvailable doesn't get rescued here?

PG::LockNotAvailable It is a parent error, the current error being ActiveRecord::LockWaitTimeout. Hence you can find it in e.cause

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment