Ubuntu 12.10 で PHP 5.4.12 を実行しています。
エラーハンドラーを使用してPHPエラーを例外に変換し、処理できるようにしています。ただし、エラーを例外に変えることはできますが、例外をキャッチする方法はまったくないようです。
簡単なデモ コードを次に示します。
<?php
class CErrorException extends Exception {}
function handleError($level, $message, $file, $line){
if( error_reporting() != 0){
throw new CErrorException($message, $level);
}
}
function handleException(Exception $exception){
var_dump('Exception handled at global level');
}
set_error_handler('handleError');
set_exception_handler('handleException');
try {
require_once('non\existent\file'); //Will generate an error and cause an exception to be thrown.
} catch (Exception $e) {
var_dump("let's deal with the exception");
}
require_once
残念ながら、この場合、スローされた例外をキャッチすることはできません。そのため、存在しないファイルや読み取り不可能なファイルで使用することによって引き起こされた問題から回復するのが難しくなります。
次の 2 つのエラーが表示されます。
Warning: Uncaught exception 'CErrorException' with message 'require_once(non\existent\file): failed to open stream: Invalid argument' in /work/test.php:7 Stack trace: #0 /work/test.php(20): handleError(2, 'require_once(no...', '/work/test.php', 20, Array) #1 /work/test.php(20): require_once() #2 {main} thrown in /work/test.php on line 7
Fatal error: main(): Failed opening required 'non\existent\file'
捕まえるしか方法はないのでしょうか?