PHP PDO error handling

Asked

Viewed 1,601 times

3

In PHP, how to make the PDO not to issue FATAL error, so that it is possible to identify and treat the error occurred?

Example: Table: tb_requests: id fk_products Qtd 1 5 5 2 7 2 3 2 13

Table: tb_products id description 5 mango 7 Grape 2 Peach

Whereas there is relationship amid tb_orders.fk_products and tb_products.id.

If I try to delete Manga (id = 5) from the table tb_products...

$sql = "DELETE FROM tb_produtos where id = ?"; // query
$rs = $this->conn->prepare($sql); // prepara a query
$arParametros = array(5); // parametro(s) para a query
try {
  $teste = $rs->execute($arParametros); // executa query
} catch (PDOException $err) {// DEVERIA TRATAR EXCEÇÕES PDO
        echo "ERRO PDO.....<br/>";
        var_dump($err->getMessage());
        var_dump($this->conn->errorInfo());
        echo '...fim erros PDO....';
} catch (Exception $err) {// DEVERIA TRATAR OUTRAS EXCEÇÕES (NÃO PDO)
        echo "ERRO NÃO PDO.....<br/>";
        var_dump($err);
        echo "FIM ERRO NÃO PDO.....<br/>";
}

...however, never enters the CATCH, generates the error below and script execution is terminated:

Fatal error: Uncaught Exception 'Pdoexception' with message 'SQLSTATE[23000]: Integrity Constraint Violation: 1451 Cannot delete or update a Parent Row: a Foreign key Constraint fails....

How do I not close the script execution? That is, enter CATCH and make it possible to handle the error?

Notes:

In connection I use:

$this->conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$this->conn->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);

My environment:

  • PHP 5.6
  • Mysql 5.5
  • http://stackoverflow.com/questions/8439581/catching-multiple-exception-types-in-one-catch-block/19325523#19325523

  • i) Declared use of class \Pdoexception? ii) } catch (\PDOException $err) {

  • 1

    @Papacharlie It was exactly that, just put the backslash before Pdoexception.... thank you very much! If you can, post the answer that mark her now.

  • That goes for catch (Exception $err) also. Every class I declare below the namespace to avoid having to declare with backslash and eventually a forgetfulness.

1 answer

4


In case you’re wearing namespace declare the class with the backslash just below the namespace, use \PDOException, or in the code block itself catch (\PDOException $err).

namespace XXX;
use \PDOException;
...
catch (PDOException $err)

or

namespace XXX;
...
catch (\PDOException $err)
  • 1

    Thank you so much for your help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.