PDOException::getCode() returns the SQLSTATE for a database failure, so its value may be a five-character string such as 42S02. Do not pass it to code that requires an integer exception code. Use errorInfo when the database driver code and message are also needed.
Last updated: October 28, 2026.
<?php
$pdo = new PDO($dsn, $username, $password, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
try {
$pdo->query('SELECT * FROM missing_table');
} catch (PDOException $error) {
$sqlState = (string) $error->getCode();
[$state, $driverCode, $driverMessage] =
$error->errorInfo ?? [$sqlState, null, null];
error_log(sprintf(
'Database failure: SQLSTATE=%s driver=%s message=%s',
$state,
$driverCode ?? 'n/a',
$driverMessage ?? 'n/a'
));
throw new RuntimeException('Database operation failed.', 0, $error);
}The application log keeps the structured diagnostic details, while the replacement exception exposes a neutral message. Passing the original exception as previous preserves its stack trace for server-side debugging.
Keep SQLSTATE separate from driver codes
The PDOException documentation defines its code as int|string and identifies it as SQLSTATE. SQLSTATE is a standardized five-character identifier; it is not the same value as a MySQL, PostgreSQL, SQLite, or SQL Server native error number.
The exception’s errorInfo property corresponds to the array returned by PDO::errorInfo(): element 0 is SQLSTATE, element 1 is the driver-specific code, and element 2 is the driver message. Some elements can be null, so handle them defensively.
Branch only on stable information
Use SQLSTATE classes for portable decisions when possible. For example, class 23 represents integrity-constraint violations. Use a complete state or driver code only when the recovery behavior truly depends on a specific database and the code is documented by that vendor.
Do not parse the human-readable exception message to make program decisions, and do not display it to visitors because it may reveal schema or connection details. Catch only failures the application can resolve, then allow unexpected database failures to reach the outer error boundary. Continue with connecting with PDO_SQLSRV, understanding PHP throwable errors, and diagnosing an unknown-column error.