Klasė ErrorException
Klasė ErrorException paveldi iš bazinės klasės Exception ir naudojama
PHP klaidų transformavimui į išimtis. Ji prie standartinės išimčių funkcionalumo prideda
informaciją apie klaidos sunkumą (severity). Klasė yra ypač naudinga
naudojant su funkcija set_error_handler.
Sintaksė
new ErrorException(
string $message = "",
int $code = 0,
int $severity = E_ERROR,
string $filename = __FILE__,
int $lineno = __LINE__,
Throwable $previous = null
);
Pavyzdys
Sukurkime ir apdorokime ErrorException:
<?php
try {
throw new ErrorException('Critical error', 0, E_ERROR);
} catch (ErrorException $e) {
echo 'Error: ' . $e->getMessage();
echo ' Severity: ' . $e->getSeverity();
}
?>
Kodo vykdymo rezultatas:
'Error: Critical error Severity: 1'
Pavyzdys
Paverskime standartines PHP klaidas į išimtis:
<?php
function errorHandler($severity, $message, $file, $line) {
throw new ErrorException($message, 0, $severity, $file, $line);
}
set_error_handler('errorHandler');
try {
strpos(); // Neteisingas argumentų kiekis
} catch (ErrorException $e) {
echo 'Caught exception: ' . $e->getMessage();
echo ' in ' . $e->getFile();
echo ' on line ' . $e->getLine();
}
?>
Kodo vykdymo rezultatas (pavyzdys):
'Caught exception: strpos() expects at least 2 parameters, 0 given in /path/to/file.php on line 10'
Pavyzdys
Gaukime informaciją apie klaidos sunkumą:
<?php
try {
throw new ErrorException('Warning message', 0, E_WARNING);
} catch (ErrorException $e) {
echo 'Severity level: ' . $e->getSeverity();
echo ' Is warning: ' . ($e->getSeverity() === E_WARNING ? 'yes' : 'no');
}
?>
Kodo vykdymo rezultatas:
'Severity level: 2 Is warning: yes'
Taip pat žiūrėkite
-
klasė
Exception,
bazinė klasė visoms išimtims PHP -
funkciją
set_error_handler,
kuri nustato vartotojo apibrėžtą klaidų tvarkytuvą