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!
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!
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
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;
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