Try / Catch PDOException does not work when error occurs

2

I created the following method to execute my querys:

public function setQuery($query) {
    try {
        $stmt = self::$conn->prepare($this->limpaQuery($query));
        return $stmt->execute();
    } catch (PDOException $Exception) {
        var_export($query);
        die();
    }
}

It works perfectly, but when I run a wrong query it has the following error:

  

Fatal error: Uncaught exception 'PDOException' with message   'SQLSTATE [42S22]: Column not found: 1054 Unknown column ...

What I do not understand is why it does not get PDOException, I wanted every query that it did not execute to be displayed.

Updade

/**
 * Conexao
 */
public function openConection() {
    try {

        //Verifica se uma instancia já existe
        if (!isset(self::$conn)) {
            //String de conexão
            self::$conn = new PDO("mysql:host=$this->servername;dbname=$this->banco", $this->username, $this->password);

            // set the PDO error mode to exception
            self::$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }

        //Mensagem de status
        $this->status = "Conectado no host $this->servername, no banco dbname=$this->banco com o usuário $this->username";
    } catch (PDOException $e) {
        //Mensagem de status
        $this->status = "Falha ao tentar conectar: \n" . $e->getMessage();
    }
}
    
asked by anonymous 12.11.2017 / 01:03

2 answers

3

I found the problem, it was interpreting the PDOException as connection \ PDOException because of the namespace.

namespace conexao;

So I imported the PDOException.

use PDOException;

Source: link

    
12.11.2017 / 01:51
2

You need to set the PDO :: ATTR_ERRMODE setting to PDO :: ERRMODE_EXCEPTION .

$conn = new PDO($host, $usuario, $senha);
$conn->setAttribute(PDO::ATTR_ERRMODE, $conn::ERRMODE_EXCEPTION);
    
12.11.2017 / 01:31