Reputation: 10599
I am trying to get up and running with stored procedures in Zend Framework 2. I tried to return an error code with an out parameter in the stored procedure, but I have been unable to make that work. Then I thought that when an error occurred, I could just catch an exception in PHP. The problem is that I can't seem to get access to the specific error code - only a general one (e.g. 23000 - integrity constraint violation). 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 check exactly which error occurred. The problem, though, is that the exception that is thrown has an error code of 23000 and not one of the above.
An InvalidQueryException
is 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);
}
The PDOException
here contains an error code of 23000 in my case. The null
parameter is the error code. So in my catch block, I will actually be catching an InvalidQueryException
with an error code of 0, which is not all that useful. This exception does provide me access to previous exceptions (the last parameter above), which would be the PDOException
, like this:
// try block omitted
catch (InvalidQueryException $e) {
$previous_exception_error_code = $e->getPrevious()->getCode();
}
On duplicate entry (1062), the error code is 23000. For a "cannot add or update a child row" (1452), it would also be 23000. Therefore I am not sure how I can distinguish between them in my application. What if I wanted to present different error messages to the user for the two errors? The exception message is: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'user' for key 'username'
. This is a string, though, so searching for the error code would just be too hacky. I am hoping to be able to still abstract away from the fact that I am using PDO as the concrete implementation.
In the end, this seems more about PDO and MySQL than ZF2. I am not really sure where to go from here, so any ideas on how I can distinguish between the error codes would be much appreciated. That is, to know when an error 1062 or 1452 occurred rather than just 23000.
Upvotes: 4
Views: 2461
Reputation: 1532
may be it will help some body-> sometimes the try catch block is not efficient read here the comments
and here the solution.
Upvotes: 0
Reputation: 125875
You want to switch on $e->errorInfo[1]
, which is the driver-specific error code (instead of the standardised SQLSTATE
value).
Upvotes: 6