如何从REST服务中捕获错误?

时间:2017-01-11 16:47:40

标签: php

我正在开发PHP休息服务。许多错误导致PHP终止而没有深入了解原因。在try catch子句中包含我的函数没有帮助,脚本退出而不进入catch块。有没有办法捕获我的PHP脚本中的所有/任何错误?

1 个答案:

答案 0 :(得分:1)

检查error_log。很可能是PHP FATAL错误在Exception之前被抛出,所以它在catch语句之前已经死了。

使用register a shutdown function在应用程序中记录所有内容error_get_last()。例如,这将记录将导致应用程序意外死亡的所有错误。

function shutdown()
{
    $arrError = error_get_last();

    if( is_null($arrError) ) {
        return true;
    }

    //Remove the if statement and just have the error_log() if you want to log everything
    if( in_array($arrError['type'], array(E_RECOVERABLE_ERROR, E_ERROR, E_USER_ERROR)) ) { //FATAL HANDLER!
       error_log("Error caught. ". $arrError['message'] ." in file ". $arrError['file'] .":". $arrError['line']);

       //Then maybe do something to make this verbose in your development environment
       if( ENVIRONMENT == "dev" ) {
           echo "<h3>ERROR</h3> ". $arrError['message'] ." in file ". $arrError['file'] .":". $arrError['line'];
           die;
       }
    }

}

register_shutdown_function('shutdown');