Talker
(Talker)
July 8, 2014, 12:06pm
1
Hi
How can I get an error code occurred in the database (ORACLE) ?
I can get error message $e->getMessage()
And also get some code $e->getCode (), but it bears no relation to the database error code …
If I get the code, I would react differently but I don’t know how to get it.
Can anyone give me a hint?
Keith
(Kburton)
July 8, 2014, 12:27pm
2
Assuming you’re catching a CDbException, you can access the errorInfo property.
Talker
(Talker)
July 9, 2014, 12:44pm
3
The errorInfo property is empty when I catch an exception in saveModel() method of the Controler
CDbException Object
(
[errorInfo] =>
[message:protected] => CDbCommand failed to execute the SQL statement: ORA-00001: unique constraint (INV.INV_REF_USR_KEY) violated. The SQL statement executed was: INSERT INTO "INV"."INV_REF_USR" ("USR", "TAB_NUM") VALUES (:yp0, :yp1). Bound with :yp0='JOHN', :yp1='12345'
[string:Exception:private] =>
[code:protected] => 0
[file:protected] => X:\home\framework\db\CDbCommand.php
[line:protected] => 358
[trace:Exception:private] => Array
....
)
Keith
(Kburton)
July 9, 2014, 12:48pm
4
Is anything returned by the getPrevious() method?
Talker
(Talker)
July 10, 2014, 6:55am
5
$e->getPrevious() returns nothing
Keith
(Kburton)
July 10, 2014, 9:45am
6
I’m surprised that neither of those have the required information. I don’t like to suggest this, but maybe you’re going to have to extract it from the error message.
Given that you’re already going to be tied to a database vendor (as you want to recognise specific error codes), something like this might work well enough to get the code from the second colon delimited section:
$errorArray = explode(':', $e->getMessage());
$errorCode = isset($errorArray[1]) ? trim($errorArray[1]) : '';
Or something slightly more robust checking for the expected pattern:
$errorArray = array();
$errorCode = preg_match('/ORA-\d{5}/', $e->getMessage(), $errorArray)
? $errorArray[0]
: '';
I hope there’s a better option though.
Talker
(Talker)
July 10, 2014, 3:05pm
7
I do extract the error code from message something like this:
$msgText = $exception->getMessage();
$posStart = mb_stripos(mb_upper($msgText), 'ORA-');
$errorCode = $posStart ? mb_substr($msgText, $posStart, 9) : false;
switch ($errorCode) {
case 'ORA-00001':
$msgText = 'KEY VIOLATION';
break;
case ...
}
return $msgText;
I have a lack of experience with regular expressions, so thanks for your code.))
I hope there’s a better option too…
Thanks a lot anyway. I appreciate your assistance.