LoginSignup
9
11

More than 5 years have passed since last update.

set_error_handlerではfatal errorはハンドリングしてくれない

Last updated at Posted at 2012-04-17

問題点

set_error_handlerは、phpのERRORやNOTICEなどが発生した際に実行する関数を指定できるが、FATAL_ERROR(例外)の場合は関数を実行してくれない。

not_working.php
set_error_handler('error_handler');

throw new Exception('hoge');

function('error_handler')
{
    echo 'ERROR!!';
}

上記では'ERROR!!'は出力されない

解決策

register_shutdown_functionという関数を使う。

working.php
register_shutdown_function('shutdown_handler');

throw new Exception('foo');

function('shutdown_handler')
{
    echo 'ERROR!!';
}

上記は'ERROR!!'が出力される。

メソッド指定の場合

set_error_handlerもそうだが、メソッドを指定したい場合は

use_method.php
$foo = new Foo();
register_shutdown_function(array($foo, 'bar'));


class Foo{
    function bar()
    {
        echo 'ERROR!!';
    }
}

このように行う。

補足1

今回に限っては解決しますが、FATAL_ERRORを拾っているというわけではないので、厳密には違いますね・・・。まあphpのFATAL_ERRORは回避できないっぽいのでほぼ同義なのでしょうが、なにかいい方法を知ってる方いましたら教えて下さいませ。

詳細はマニュアルページを見て下さい。

補足2

set_exception_handlerのほうが適切かもしれない。

参考

9
11
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
9
11