Laravel docs recommends using attempts to deal with Deadlocks (https://shorturl.at/bsKta)
But, the handleTransactionException() method inside the transaction() method has a comment:
On a deadlock, MySQL rolls back the entire transaction so we can’t just retry the query. We have to throw this exception all the way out and let the developer handle it in another way. We will decrement too.
Does it mean to handle Deadlocks I should wrap the DB::transaction() with a try/catch? What’s the use of attempts then in this case?
2
Answers
As mentioned in the Larave Doc,
attempts
means:But about using
try/catch
, I can say that when MySQL reaches a deadlock, it will throw an exception.try/catch
allows you to do something with an Exception. For e.g:Yes, you should wrap
DB::transaction()
in atry/catch
block to handle deadlocks. Although Laravel’sattempts
parameter allows retries for some errors, deadlocks are special because MySQL rolls back the entire transaction. Therefore, Laravel can’t automatically retry it, and you need to handle deadlocks manually.Here’s a simple approach:
try/catch
.1213
or40001
).Example code:
This way, you manually retry the transaction on deadlocks.