Laravel Doc recommends using attempts to deal with Deadlocks.
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?
As mentioned in the Larave Doc, attempts
means:
Specifies the number of times a transaction should be retried when a deadlock occurs.
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:
try {
DB::transaction(function () {
// Your transaction logic
}, 5); // Laravel will attempt the transaction up to 5 times
} catch (Exception $e) {
// Handle the error after all attempts fail
// For example, you can log the error or show a message to the user
Log::warning($e->getMessage());
}