Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dealing with PDOException's when DB return an Error Statement

I would like to know how exactly I can deal with the error's statements returned by DataBase Drivers available in PDO class.

As example, let's take the UNIQUE Fields as study-case.

As you should know, at least when PDO's Debug Mode is active, when trying to add something duplicated in a Database's UNIQUE Field, we receive a PDOException.

And I would like to know what is the correct way to handle this. I searched about it and I've got this:

try {

    // PDO::prepare(), PDOStatement::execute e etc.

} catch( PDOException $e ) {

    if( $e -> getCode() == 23000 ) {
        // Do something
    }
}

But I'm not sure if it's correct and, thinking as programmer, is this really a good practice? I mean, rely on the Error Code?

Even worse: PDO accepts multiple drivers, all they share the same Error Code?

Of course this is not the only case. There are several other Error Codes, right? This "technique" can be used in all the circumstances?

like image 727
Bruno Augusto Avatar asked May 14 '11 11:05

Bruno Augusto


1 Answers

After looking at http://php.net/manual/en/class.pdoexception.php, I get the feeling that you might need to rely on $e->getMessage() to find out what the error was.

Reading through one of the posts provided, you may need to extract the correct error code from the message.

PDO seems to have been programmed in a fairly weird way! But it's still pretty invaluable when dealing with multiple database types!

like image 139
Darkzaelus Avatar answered Oct 02 '22 07:10

Darkzaelus