Working with PDOException when DB returns an error message

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

As an example, take UNIQUE Fields as a case study.

As you know, at least when the PDO debugging mode is active, when we try to add something duplicated in the UNIQUE field of the database, we get a PDOException.

And I would like to know what is the right way to handle this. I searched about this and I have this:

try { // PDO::prepare(), PDOStatement::execute e etc. } catch( PDOException $e ) { if( $e -> getCode() == 23000 ) { // Do something } } 

But I'm not sure if this is correct and, thinking a programmer, is this really good practice? I mean rely on an error code?

Even worse: PDO accepts multiple drivers, all of them have the same error code?

Of course, this is not the only case. There are a few more error codes, right? Can this โ€œtechniqueโ€ be used in all circumstances?

+6
source share
1 answer

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.

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

PDO seems to be programmed pretty weird! But this is still pretty priceless when working with several types of databases!

+3
source

Source: https://habr.com/ru/post/888101/


All Articles