Deadlock exception code for PHP, MySQL PDOException?

前端 未结 2 1492
北海茫月
北海茫月 2020-12-17 04:30

Using PHP PDO MySQL, exception mode.

Does a PDOException code for [MySQL] deadlocks exist?

Is there an alternative if it doesn\'t?

相关标签:
2条回答
  • 2020-12-17 04:36

    I encountered a situation where the above example was not enough as the \PDOException was caught and thrown again with an other message. I had to catch \Throwable and check all the $exc->getPrevious() to see if it was instaceof \PDOException. As a safety net if the error was not instance of \PDOException I checked the error message to see if it contains the phrase 'try restarting transaction'

    0 讨论(0)
  • 2020-12-17 04:43

    PDO::errorInfo, PDOException::errorInfo

    MySQL Server Error Codes and Messages; Error: 1213 SQLSTATE: 40001 (ER_LOCK_DEADLOCK)

    /*[...]*/
    
    //error mode is exception
    $pdoDBHandle->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
    
    try
    {
        /*[...]*/
    }
    catch(\PDOException $exc)
    {
        if(
            $exc->errorInfo[0]==40001 /*(ISO/ANSI) Serialization failure, e.g. timeout or deadlock*/;
    
            && $pdoDBHandle->getAttribute(\PDO::ATTR_DRIVER_NAME)=="mysql"
            && $exc->errorInfo[1]==1213  /*(MySQL SQLSTATE) ER_LOCK_DEADLOCK*/
        )
        {
            /*[...]*/
        }
        else
            throw $exc;
    }
    
    0 讨论(0)
提交回复
热议问题