Hàm set_exception_handler
Hàm set_exception_handler cho phép xác định một hàm sẽ được gọi để xử lý các ngoại lệ không được bắt. Tham số truyền vào là tên hàm xử lý hoặc một hàm ẩn danh. Trình xử lý nhận đối tượng ngoại lệ làm tham số.
Cú pháp
set_exception_handler(callable $exception_handler): callable
Ví dụ
Thiết lập trình xử lý ngoại lệ đơn giản:
<?php
function myExceptionHandler($exception) {
echo 'Caught exception: ' . $exception->getMessage();
}
set_exception_handler('myExceptionHandler');
throw new Exception('Something went wrong!');
?>
Kết quả thực thi mã:
'Caught exception: Something went wrong!'
Ví dụ
Sử dụng hàm ẩn danh làm trình xử lý:
<?php
set_exception_handler(function($exception) {
echo 'Error: ' . $exception->getMessage();
});
throw new Exception('Critical error');
?>
Kết quả thực thi mã:
'Error: Critical error'
Ví dụ
Khôi phục trình xử lý trước đó:
<?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(); // Khôi phục firstHandler
throw new Exception('Test');
?>
Kết quả thực thi mã:
'First handler: Test'