Handle query postgres errors

Asked

Viewed 621 times

0

Using PDO and Postgres, but with difficulty to get the query Exception, for example error in syntax.

I’m grateful if anyone can shed some light!!

  • I think that that answers, if you do not post your code in the question.

  • Can you put here the part of the code you already have? <br> Or even the error? It would be easier to analyze

  • then, I want to implement the catch and return any error messages that there might be, as a non-existent column, errors that do not allow the query to run. Thank you!!!

1 answer

1


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

  • PDO::ERRMODE_SILENT - to obtain errors via errorcode and errorInfo;
  • PDO::ERRMODE_WARNING - to issue WARNING;
  • PDO::ERRMODE_EXCEPTION: - to make exceptions.

By default it comes with PDO::ERRMODE_SILENT which reports errors via 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;

  1. Error code sql state.
  2. According to driver error code used.
  3. Error message issued by driver.

As in your case you want to deal with the exceptions, we will have to change the PDO error control strategy as follows:

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

or 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 the methods

  • getMessage() - Returns the Exception message.
  • getFile() - Get the name of the file from which the exception was created.
  • getline() - The error line.
  • getTrace() - Returns the rest of the stack.
  • Great Nelson, my question was why he did not return getMessage() perfectly explained by you, I will put in practice here in the code

Browser other questions tagged

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