関数 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'