Функција set_exception_handler
Функција set_exception_handler омогућава да се дефинише функција која ће бити позвана да обради неприхваћене изузетке. У параметар се прослеђује име функције-обрађивача или анонимна функција. Обрађивач добија објекат изузетка као параметар.
Синтакса
set_exception_handler(callable $exception_handler): callable
Пример
Поставимо једноставан обрађивач изузетака:
<?php
function myExceptionHandler($exception) {
echo 'Caught exception: ' . $exception->getMessage();
}
set_exception_handler('myExceptionHandler');
throw new Exception('Something went wrong!');
?>
Резултат извршавања кода:
'Caught exception: Something went wrong!'
Пример
Коришћење анонимне функције као обрађивача:
<?php
set_exception_handler(function($exception) {
echo 'Error: ' . $exception->getMessage();
});
throw new Exception('Critical error');
?>
Резултат извршавања кода:
'Error: Critical error'
Пример
Враћање претходног обрађивача:
<?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(); // Враћа firstHandler
throw new Exception('Test');
?>
Резултат извршавања кода:
'First handler: Test'