Try/Catch Pdoexception does not work when error occurs

Asked

Viewed 1,622 times

3

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 shows the following error:

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

What I don’t understand is why it doesn’t take Pdoexception, I wanted every query that doesn’t run to be displayed.

Height

/**
 * 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();
    }
}

2 answers

3

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

$conn = new PDO($host, $usuario, $senha);
$conn->setAttribute(PDO::ATTR_ERRMODE, $conn::ERRMODE_EXCEPTION);
  • Already this way :/

  • Then add as well setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

  • Gave the same effect

  • Strange because I tested it here and it works.

  • I posted the answer, it was because of the namespace.

  • 1

    I saved even as a favorite, who save a day happens then I know where to find. :)

Show 1 more comment

3


  • Well I was going to ask this in the comments, but I did not remember if there was an undefined class error when using on catch.

  • The strange thing was this, it did not give undefined class error @Andersoncarloswoss

  • I had the same problem. I started to implement namespace in the classes and Pdoexecption stopped working as expected.

Browser other questions tagged

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