Exception::getCode
(PHP 5 >= 5.1.0)
Exception::getCode — Gets the Exception code
Parameters
This function has no parameters.
Return Values
Returns the exception code as integer in Exception but possibly as other type in Exception descendants (for example as string in PDOException).
Examples
Example #1 Exception::getCode() example
<?php
try {
throw new Exception("Some error message", 30);
} catch(Exception $e) {
echo "The exception code is: " . $e->getCode();
}
?>
The above example will output something similar to:
The exception code is: 30
- Функция Exception::__construct() - Создать исключение
- Функция Exception::getMessage() - Получает сообщение исключения
- Функция Exception::getPrevious() - Возвращает предыдущее исключение
- Функция Exception::getCode() - Получает код исключения
- Функция Exception::getFile() - Получает файл, в котором возникло исключение
- Функция Exception::getLine() - Получает строку, в которой возникло исключение
- Функция Exception::getTrace() - Получает трассировку стека
- Функция Exception::getTraceAsString() - Получает трассировку стека в виде строки
- Функция Exception::__toString() - Строковое представление исключения
- Функция Exception::__clone() - Клонировать исключение
Коментарии
when raising an Exception with no error code explicitly defined, getCode() returns the integer 0
<?php
try {
throw new Exception("no code!!");
} catch (Exception $e) {
print("Code='" . $e->getCode() . "'");
}
?>
outputs
Code='0'
The exception code can be used to categorize your errors. If you're wondering what the exception code can be used for, read on below.
Let's say each time your application isn't able to connect to the database, you can save the error message under the error/exception code 214. At the end of the month, you can do a quick search on the error number '214' and find out how many times this error occurred. This makes life easier. Also, the error/exception message will give you details into what happened.
The point is to use both the exception message and code. It's helpful in the long run.
Note: I added this note, because I was confused earlier as to the purpose of the exception code and it's use.
Do not use the strict operator as suggested when checking the Exception Code in \PDOException.
As per documentation: \PDOException is returning a string for its Exception Code and not an Integer.
Ran into the following in PHP8:
<?php
catch(\PDOException $e) {
var_dump($e->getCode()); //Output: string(5) "23000"
}
?>