Handling postgres query errors [closed]

0

To use PDO and Postgres, but with difficulty to catch the exception of the query, such as error in the syntax.

I am grateful for a light!

    
asked by anonymous 19.05.2016 / 17:08

1 answer

1

As you want to implement this in the catch block, first thing is to change the strategy of error controls of the PDO, there are 3 strategies

  • PDO :: ERRMODE_SILENT - to get errors via errorCode and errorInfo;
  • PDO :: ERRMODE_WARNING - to issue WARNING;
  • PDO :: ERRMODE_EXCEPTION: - to issue exceptions.

By default it comes with PDO :: ERRMODE_SILENT which informs errors through errorCode () and errorInfo (), which would be caught this way:

try {
   $pdo = new DBClass();
} catch (PDOException $e) {
   exit(1);
}

$sql = 'SELECT * FROM TABELA';
$stmt = $pdo->query($sql);
if (!$stmt) {
    list($erro, $erro_driver, $msg_driver) = $pdo->errorInfo();
    switch ($erro) {
       case '42000':
           //ERRO DE SINTAXE SEU TRATAMENTO AQUI... 
           exit(1);
...
}

}

errorInfo () returns an array of three positions;

  • sql state error code.
  • According to the driver error code used.
  • Error message issued by the driver.
  • As in your case you want to handle the exceptions, we will have to change the PDO error-control strategy as follows:

    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    

    ie the same code above would look like this:

    try {
       $pdo = new DBClass();
    } catch (PDOException $e) {
       exit(1);
    }
    
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    $sql = 'SELECT * FROM TABELA';
    try{
       $stmt = $pdo->query($sql);
    }catch(PDOException $e) {
       switch ($e->getCode()) {
           case '42000':
               //ERRO DE SINTAXE SEU TRATAMENTO AQUI... 
               exit(1);
       ...
       }
    }
    

    )

    The PDOException class still has methods

    • getMessage () - Returns the Exception message.
    • getFile () - Gets the name of the file where the exception was created.
    • getLine () - The error line.
    • getTrace () - Returns the rest of the stack.
    19.05.2016 / 22:27