Exception::getCode

(PHP 5, PHP 7, PHP 8)

Exception::getCode β€” ΠŸΠΎΠ»ΡƒΡ‡Π°Π΅Ρ‚ ΠΊΠΎΠ΄ ΠΈΡΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΡ

ОписаниС

final public function Exception::getCode(): int

Π’ΠΎΠ·Π²Ρ€Π°Ρ‰Π°Π΅Ρ‚ ΠΊΠΎΠ΄ ΠΈΡΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΡ.

Бписок ΠΏΠ°Ρ€Π°ΠΌΠ΅Ρ‚Ρ€ΠΎΠ²

Π‘ΠΈΠ³Π½Π°Ρ‚ΡƒΡ€Π° Ρ„ΡƒΠ½ΠΊΡ†ΠΈΠΈ Π½Π΅ содСрТит ΠΏΠ°Ρ€Π°ΠΌΠ΅Ρ‚Ρ€ΠΎΠ².

Π’ΠΎΠ·Π²Ρ€Π°Ρ‰Π°Π΅ΠΌΡ‹Π΅ значСния

ΠœΠ΅Ρ‚ΠΎΠ΄ Π²ΠΎΠ·Π²Ρ€Π°Ρ‰Π°Π΅Ρ‚ ΠΊΠΎΠ΄ ΠΈΡΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΡ Ρ‚ΠΈΠΏΠ° int Ρƒ класса Exception, Π½ΠΎ Ρƒ ΠΏΠΎΡ‚ΠΎΠΌΠΊΠΎΠ² класса Exception ΠΌΠΎΠΆΠ΅Ρ‚ Π±Ρ‹Ρ‚ΡŒ Π΄Ρ€ΡƒΠ³ΠΎΠΉ Ρ‚ΠΈΠΏ (Π½Π°ΠΏΡ€ΠΈΠΌΠ΅Ρ€, Ρ‚ΠΈΠΏΠ° string Π² PDOException).

ΠŸΡ€ΠΈΠΌΠ΅Ρ€Ρ‹

ΠŸΡ€ΠΈΠΌΠ΅Ρ€ #1 ΠŸΡ€ΠΈΠΌΠ΅Ρ€ использования ΠΌΠ΅Ρ‚ΠΎΠ΄Π° Exception::getCode()

<?php
try {
throw new
Exception("КакоС-Π½ΠΈΠ±ΡƒΠ΄ΡŒ сообщСниС ΠΎΠ± ошибкС", 30);
} catch(
Exception $e) {
echo
"Код ΠΈΡΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΡ: " . $e->getCode();
}
?>

Π’Ρ‹Π²ΠΎΠ΄ ΠΏΡ€ΠΈΠ²Π΅Π΄Ρ‘Π½Π½ΠΎΠ³ΠΎ ΠΏΡ€ΠΈΠΌΠ΅Ρ€Π° Π±ΡƒΠ΄Π΅Ρ‚ ΠΏΠΎΡ…ΠΎΠΆ Π½Π°:

Код ΠΈΡΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΡ: 30

Π‘ΠΌΠΎΡ‚Ρ€ΠΈΡ‚Π΅ Ρ‚Π°ΠΊΠΆΠ΅

  • Throwable::getCode() - Π’ΠΎΠ·Π²Ρ€Π°Ρ‰Π°Π΅Ρ‚ ΠΊΠΎΠ΄ ΠΈΡΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΡ
οΌ‹Π”ΠΎΠ±Π°Π²ΠΈΡ‚ΡŒ

ΠŸΡ€ΠΈΠΌΠ΅Ρ‡Π°Π½ΠΈΡ ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Π΅ΠΉ 3 notes

up
79
talksonweb at gmail dot com ΒΆ
12 years ago
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.
up
33
ricky at rocker dot com ΒΆ
13 years ago
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'
up
6
2M ΒΆ
4 years ago
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"
}

?>