Funksioni set_exception_handler
Funksioni set_exception_handler lejon përcaktimin e një funksioni që do të thirret për trajtimin e përjashtimeve të pa kapura. Në parametër kalohet emri i funksionit-trajtues ose një funksion anonim. Trajtuesi merr objektin e përjashtimit si parametër.
Sintaksa
set_exception_handler(callable $exception_handler): callable
Shembull
Le të vendosim një trajtues të thjeshtë përjashtimesh:
<?php
function myExceptionHandler($exception) {
echo 'Caught exception: ' . $exception->getMessage();
}
set_exception_handler('myExceptionHandler');
throw new Exception('Something went wrong!');
?>
Rezultati i ekzekutimit të kodit:
'Caught exception: Something went wrong!'
Shembull
Përdorimi i funksionit anonim si trajtues:
<?php
set_exception_handler(function($exception) {
echo 'Error: ' . $exception->getMessage();
});
throw new Exception('Critical error');
?>
Rezultati i ekzekutimit të kodit:
'Error: Critical error'
Shembull
Rikthimi i trajtuesit të mëparshëm:
<?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(); // Rikthen firstHandler
throw new Exception('Test');
?>
Rezultati i ekzekutimit të kodit:
'First handler: Test'