How To Get A Db Error Code?

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?

Assuming you’re catching a CDbException, you can access the errorInfo property.

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

....

)

:frowning:

Is anything returned by the getPrevious() method?

$e->getPrevious() returns nothing

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.

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.