Informational advisory: Session upload progress

PDOException::getCode

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

PDOException::getCode — Gets the SQLSTATE error code

Descrizione

final public function PDOException::getCode(): int|string

Returns the exception code. This is the inherited Exception::getCode(), but unlike in most other exceptions, the code is usually a string.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

Returns the SQLSTATE as a five-character string (for example "42S02" or "HY000"), see PDO::errorCode().

If the connection fails in PDO::__construct(), returns the driver-specific error code as an int instead (for example 1045 for access denied in MySQL).

Attenzione

The code parameter of Exception::__construct() only accepts an int, so passing this value to it when rethrowing the error as a different exception throws a TypeError. Casting it to int loses information ("HY000" becomes 0). Pass the original exception as the previous parameter instead.

Esempi

Example #1 PDOException::getCode() example

<?php
$pdo = new PDO('sqlite::memory:');

try {
    $pdo->query('SELECT * FROM missing_table');
} catch (PDOException $e) {
    var_dump($e->getCode());
}
?>

Il precedente esempio visualizzerà:

string(5) "HY000"

Example #2 Rethrowing a PDOException

<?php
class DatabaseException extends RuntimeException {}

$pdo = new PDO('sqlite::memory:');

try {
    try {
        $pdo->query('SELECT * FROM missing_table');
    } catch (PDOException $e) {
        // Passing $e->getCode() as the code would throw a TypeError
        throw new DatabaseException('Query failed', previous: $e);
    }
} catch (DatabaseException $e) {
    echo $e->getMessage(), ': ', $e->getPrevious()->getCode(), "\n";
}
?>

Il precedente esempio visualizzerà:

Query failed: HY000

Vedere anche:

+add a note

User Contributed Notes

There are no user contributed notes for this page.
To Top