Usa la proprietà code di PDOException per leggere il SQLSTATE: vedi la documentazione di PDOException.
Per controllare lo SQLSTATE sollevato da una funzione PL/pgSQL, usa RAISE ... SQLSTATE come documentato.
Chiaro, il driver deve effettivamente riportare lo SQLSTATE perché funzioni. Ho confermato che PDO lo fa almeno in PHP 5.4.11 con PostgreSQL 9.2, usando questo esempio autonomo eseguibile con la CLI php:
<?php $pdo = new PDO('pgsql:'); $sql = <<<EOD CREATE OR REPLACE FUNCTION exceptiondemo() RETURNS void AS $$ BEGIN RAISE SQLSTATE 'UE001' USING MESSAGE = 'error message'; END; $$ LANGUAGE plpgsql EOD; $sth = $pdo->prepare($sql); if (!$sth->execute()) { die("Failed to create test function\n"); } $sql = "SELECT exceptiondemo();"; $sth = $pdo->prepare($sql); if (!$sth->execute()) { $ei = $sth->errorInfo(); die("Function call failed with SQLSTATE " . $ei[0] . ", message " . $ei[2] . "\n"); // Shortcut way: // die("Function call failed with SQLSTATE " . $sth->errorCode()); } ?> Output:
Function call failed with SQLSTATE UE001, message ERROR: error message Sostituisci il blocco dal secondo $sth->execute() alla fine con questo per mostrare che funziona anche la modalità a eccezioni:
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); try { $sth->execute(); } catch (PDOException $err) { $ei = $err->errorInfo; die("Function call failed with SQLSTATE " . $ei[0] . ", message " . $ei[2] . "\n"); // Alternate version to just get code: //die("Function call failed with SQLSTATE " . $err->getCode() . "\n"); }