PDO Error Handling
With ERRMODE_EXCEPTION set, PDO throws PDOException on errors. Catch it specifically to handle database errors separately from other exceptions.
With ERRMODE_EXCEPTION set, PDO throws PDOException on errors. Catch it specifically to handle database errors separately from other exceptions.
<?php
try {
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->execute(["id" => $id]);
$user = $stmt->fetch();
} catch (PDOException $e) {
// PDOException has an errorInfo array: [SQLSTATE, driver code, driver message]
$errorInfo = $e->errorInfo;
error_log("SQL Error [{$errorInfo[0]}]: {$errorInfo[2]}");
// Specific SQLSTATE codes
if ($e->getCode() === "23000") {
throw new DuplicateEntryException("Record already exists");
}
throw new DatabaseException("Query failed", 500, $e);
}
SQLSTATE code 23000 means integrity constraint violation — use it to detect duplicate entries on unique columns.