A specific error code from a stored procedure with PDO (in Zend Framework 2)

I am trying to start and run using stored procedures in Zend Framework 2. I tried to return an error code with the out parameter in the stored procedure, but I could not do this job. Then I thought that when the error occurred, I could just catch the exception in PHP. The problem is that I canโ€™t access the specific error code - only general (for example, 23000 - violation of the integrity constraint). Here is an example of what I want to do (or similar):

try { $result = $this->dbAdapter->query('CALL sp_register_user(?, ?)', array('username', 'password')); } catch (\Exception $e) { switch ($e->getCode()) { case 1062: // Duplicate entry break; case 1452: // Cannot add or update a child row break; } } 

That is, I would like to be able to accurately verify which error occurred. The problem, however, is that the exception thrown has an error code of 23000, and not one of the above.

An InvalidQueryException thrown in Zend\Db\Adapter\Driver\Pdo\Statement on line 220:

 try { $this->resource->execute(); } catch (\PDOException $e) { throw new Exception\InvalidQueryException('Statement could not be executed', null, $e); } 

PDOException here contains error code 23000 in my case. The null parameter is an error code. So in my catch block, I really catch an InvalidQueryException with error code 0, which is not so useful. This exception gives me access to the previous exceptions (the last parameter above), which will be a PDOException , for example:

 // try block omitted catch (InvalidQueryException $e) { $previous_exception_error_code = $e->getPrevious()->getCode(); } 

In double entry (1062), the error code is 23000. For "it is not possible to add or update a child row" (1452), it will also be 23000. Therefore, I am not sure how I can distinguish them in my expression. What if I wanted to present different error messages to the user for two errors? Exception message: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'user' for key 'username' . This is a string, however, so looking up the error code will just be too hacked. I hope that I can ignore the fact that I use PDO as a concrete implementation.

In the end, it looks more like PDO and MySQL than ZF2. I'm not quite sure where to go from here, so any ideas on how I can distinguish error codes are worth a lot of praise. That is, to know when the error 1062 or 1452 occurred, and not just 23000.

+4
source share
2 answers

You want to include $e->errorInfo[1] , which is the driver-specific error code (instead of the standard SQLSTATE value).

+6
source

maybe this will help some body -> sometimes the catch try block is not efficient read comments here

and here is the solution.

0
source

All Articles