LoginSignup
6
2

More than 5 years have passed since last update.

PHP: どのエラーハンドラが使われているか調べる方法

Posted at

フレームワークを使っていたり、set_error_handlerを使ってエラーハンドリングまわりを拡張したりしていると、エラーハンドラが複数あっていったいどのエラーハンドラが使われているのか分からなくなることがある。

そうしたときに現在アクティブなエラーハンドラを調べたくなるが、PHPにはそれをストレートにやる方法が無いので、自前でデバッグロジックを実装する必要がある。(get_error_handlerとかget_error_handlersとかあってもよさそうなのに)

このような処理を書くと、現在アクティブなエラーハンドラがどこに定義されているものなのか調べることができる:

// 仮エラーハンドラをセットすることで、現在のハンドラを取り出す
$currentHandler = set_error_handler(function(){});

// 仮エラーハンドラを取り消して、現在のハンドラに戻す
restore_error_handler();

// リフレクションで現在のハンドラの情報を取る
$handlerInfo = new \ReflectionFunction($currentHandler);

var_dump(
    // 現在のハンドラが定義されているファイル名を調べる
    $handlerInfo->getFileName(), 
    // 現在のハンドラが定義されている行数を調べる
    $handlerInfo->getStartLine()
);

これをエラーが発生している箇所の手前に置くなりしてデバッグに活用する。

$currentHandler = set_error_handler(function(){});
restore_error_handler();
$handlerInfo = new \ReflectionFunction($currentHandler);
var_dump(
    $handlerInfo->getFileName(), 
    $handlerInfo->getStartLine()
);

@unlink('/hoge'); // エラーハンドラにて処理されているエラー発生箇所
6
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
2