Klass ErrorException
Klass ErrorException pärineb baasklassist Exception ja seda kasutatakse
PHP vigade teisendamiseks eranditeks. See lisab standardsele erandite funktsionaalsusele
vea tõsiduse (severity) teabe. Klass on eriti kasulik
funktsiooniga set_error_handler kasutamisel.
Süntaks
new ErrorException(
string $message = "",
int $code = 0,
int $severity = E_ERROR,
string $filename = __FILE__,
int $lineno = __LINE__,
Throwable $previous = null
);
Näide
Loome ja töötleme ErrorExceptionit:
<?php
try {
throw new ErrorException('Kriitiline viga', 0, E_ERROR);
} catch (ErrorException $e) {
echo 'Viga: ' . $e->getMessage();
echo ' Tõsidus: ' . $e->getSeverity();
}
?>
Koodi täitmise tulemus:
'Viga: Kriitiline viga Tõsidus: 1'
Näide
Teisendame standardseid PHP vigu eranditeks:
<?php
function errorHandler($severity, $message, $file, $line) {
throw new ErrorException($message, 0, $severity, $file, $line);
}
set_error_handler('errorHandler');
try {
strpos(); // Vale argumentide arv
} catch (ErrorException $e) {
echo 'Püütud erand: ' . $e->getMessage();
echo ' failis ' . $e->getFile();
echo ' real ' . $e->getLine();
}
?>
Koodi täitmise tulemus (näide):
'Püütud erand: strpos() expects at least 2 parameters, 0 given in /path/to/file.php on line 10'
Näide
Saame teabe vea tõsidusastme kohta:
<?php
try {
throw new ErrorException('Hoiatussõnum', 0, E_WARNING);
} catch (ErrorException $e) {
echo 'Tõsidusaste: ' . $e->getSeverity();
echo ' Kas hoiatus: ' . ($e->getSeverity() === E_WARNING ? 'jah' : 'ei');
}
?>
Koodi täitmise tulemus:
'Tõsidusaste: 2 Kas hoiatus: jah'
Vaata ka
-
klass
Exception,
kõigi PHP erandite baasklass -
funktsioon
set_error_handler,
mis seab kasutaja veatöötleja