Funktsioon set_exception_handler
Funktsioon set_exception_handler võimaldab määratleda funktsiooni, mida kutsutakse välja püüdmata erandite töötlemiseks. Parameetrina edastatakse töötlejafunktsiooni nimi või anonüümne funktsioon. Töötleja saab erandi objekti parameetrina.
Süntaks
set_exception_handler(callable $exception_handler): callable
Näide
Määrame lihtsa erandite töötleja:
<?php
function myExceptionHandler($exception) {
echo 'Püütud erand: ' . $exception->getMessage();
}
set_exception_handler('myExceptionHandler');
throw new Exception('Midagi läks valesti!');
?>
Koodi täitmise tulemus:
'Püütud erand: Midagi läks valesti!'
Näide
Anonüümse funktsiooni kasutamine töötlejana:
<?php
set_exception_handler(function($exception) {
echo 'Viga: ' . $exception->getMessage();
});
throw new Exception('Kriitiline viga');
?>
Koodi täitmise tulemus:
'Viga: Kriitiline viga'
Näide
Eelneva töötleja taastamine:
<?php
function firstHandler($exception) {
echo 'Esimene töötleja: ' . $exception->getMessage();
}
function secondHandler($exception) {
echo 'Teine töötleja: ' . $exception->getMessage();
}
set_exception_handler('firstHandler');
$old_handler = set_exception_handler('secondHandler');
restore_exception_handler(); // Taastab firstHandler
throw new Exception('Test');
?>
Koodi täitmise tulemus:
'Esimene töötleja: Test'