Funcția set_exception_handler
Funcția set_exception_handler permite definirea unei funcții care va fi apelată pentru a gestiona excepțiile neprinse. Parametrul transmis este numele funcției-handler sau o funcție anonimă. Handler-ul primește un obiect excepție ca parametru.
Sintaxă
set_exception_handler(callable $exception_handler): callable
Exemplu
Să stabilim un handler simplu de excepții:
<?php
function myExceptionHandler($exception) {
echo 'Caught exception: ' . $exception->getMessage();
}
set_exception_handler('myExceptionHandler');
throw new Exception('Something went wrong!');
?>
Rezultatul executării codului:
'Caught exception: Something went wrong!'
Exemplu
Utilizarea unei funcții anonime ca handler:
<?php
set_exception_handler(function($exception) {
echo 'Error: ' . $exception->getMessage();
});
throw new Exception('Critical error');
?>
Rezultatul executării codului:
'Error: Critical error'
Exemplu
Restabilirea handler-ului anterior:
<?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(); // Restabilește firstHandler
throw new Exception('Test');
?>
Rezultatul executării codului:
'First handler: Test'