ErrorException-luokka
Luokka ErrorException periytyy perusluokasta Exception ja sitä käytetään
PHP-virheiden muuntamiseen poikkeuksiksi. Se lisää standardipoikkeustoiminnallisuuteen
tiedon virheen vakavuudesta (severity). Luokka on erityisen hyödyllinen
kun sitä käytetään funktion set_error_handler kanssa.
Syntaksi
new ErrorException(
string $message = "",
int $code = 0,
int $severity = E_ERROR,
string $filename = __FILE__,
int $lineno = __LINE__,
Throwable $previous = null
);
Esimerkki
Luodaan ja käsitellään ErrorException:
<?php
try {
throw new ErrorException('Kriittinen virhe', 0, E_ERROR);
} catch (ErrorException $e) {
echo 'Virhe: ' . $e->getMessage();
echo ' Vakavuus: ' . $e->getSeverity();
}
?>
Koodin suorituksen tulos:
'Virhe: Kriittinen virhe Vakavuus: 1'
Esimerkki
Muunnetaan standardi PHP-virheet poikkeuksiksi:
<?php
function errorHandler($severity, $message, $file, $line) {
throw new ErrorException($message, 0, $severity, $file, $line);
}
set_error_handler('errorHandler');
try {
strpos(); // Väärä määrä argumentteja
} catch (ErrorException $e) {
echo 'Kaapattu poikkeus: ' . $e->getMessage();
echo ' tiedostossa ' . $e->getFile();
echo ' rivillä ' . $e->getLine();
}
?>
Koodin suorituksen tulos (esimerkki):
'Kaapattu poikkeus: strpos() expects at least 2 parameters, 0 given in /path/to/file.php on line 10'
Esimerkki
Saadaan tieto virheen vakavuudesta:
<?php
try {
throw new ErrorException('Varoitusviesti', 0, E_WARNING);
} catch (ErrorException $e) {
echo 'Vakavuustaso: ' . $e->getSeverity();
echo ' Onko varoitus: ' . ($e->getSeverity() === E_WARNING ? 'kyllä' : 'ei');
}
?>
Koodin suorituksen tulos:
'Vakavuustaso: 2 Onko varoitus: kyllä'
Katso myös
-
luokka
Exception,
perusluokka kaikille PHP:n poikkeuksille -
funktion
set_error_handler,
joka asettaa mukautetun virhekäsittelijän