Funkcija set_exception_handler
Funkcija set_exception_handler ļauj definēt funkciju, kas tiks izsaukta, lai apstrādātu neķertos izņēmumus. Parametrā tiek padots apstrādātāja funkcijas nosaukums vai anonīma funkcija. Apstrādātājs kā parametru saņem izņēmuma objektu.
Sintakse
set_exception_handler(callable $exception_handler): callable
Piemērs
Iestatīsim vienkāršu izņēmumu apstrādātāju:
<?php
function myExceptionHandler($exception) {
echo 'Caught exception: ' . $exception->getMessage();
}
set_exception_handler('myExceptionHandler');
throw new Exception('Something went wrong!');
?>
Koda izpildes rezultāts:
'Caught exception: Something went wrong!'
Piemērs
Anonīmas funkcijas izmantošana kā apstrādātāju:
<?php
set_exception_handler(function($exception) {
echo 'Error: ' . $exception->getMessage();
});
throw new Exception('Critical error');
?>
Koda izpildes rezultāts:
'Error: Critical error'
Piemērs
Iepriekšējā apstrādātāja atjaunošana:
<?php
function firstHandler($exception) {
echo 'First handler: ' . $exception->getMessage();
}
function secondHandler($exception) {
echo 'Second handler: ' . $exception->getMessage();
}
set_exception_handler('firstHandler');
$old_handler = set_exception_handler('secondHandler');
restore_exception_handler(); // Atjauno firstHandler
throw new Exception('Test');
?>
Koda izpildes rezultāts:
'First handler: Test'