且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

安全地捕获PHP中的“允许的内存大小用尽"错误

更新时间:2021-08-14 23:16:54

根据此答案的建议,您可以使用register_shutdown_function()注册将检查error_get_last()的回调.

As this answer suggests, you can use register_shutdown_function() to register a callback that'll check error_get_last().

无论是通过@(关闭)运算符还是通过ini_set('display_errors', false)

You'll still have to manage the output generated from the offending code, whether by the @ (shut up) operator, or ini_set('display_errors', false)

ini_set('display_errors', false);

error_reporting(-1);

set_error_handler(function($code, $string, $file, $line){
        throw new ErrorException($string, null, $code, $file, $line);
    });

register_shutdown_function(function(){
        $error = error_get_last();
        if(null !== $error)
        {
            echo 'Caught at shutdown';
        }
    });

try
{
    while(true)
    {
        $data .= str_repeat('#', PHP_INT_MAX);
    }
}
catch(\Exception $exception)
{
    echo 'Caught in try/catch';
}

运行时,输出Caught at shutdown.不幸的是,没有抛出ErrorException异常对象,因为致命错误触发了脚本终止,随后仅在关闭函数中被捕获.

When run, this outputs Caught at shutdown. Unfortunately, the ErrorException exception object isn't thrown because the fatal error triggers script termination, subsequently caught only in the shutdown function.

您可以在关闭功能中检查$error阵列以获取原因的详细信息,然后做出相应的响应.一种建议可能是针对您的Web应用程序(使用其他地址,或者当然使用不同的参数)重新发送请求,然后返回捕获的响应.

You can check the $error array in the shutdown function for details on the cause, and respond accordingly. One suggestion could be reissuing the request back against your web application (at a different address, or with different parameters of course) and return the captured response.

尽管如此,我还是建议保持error_reporting()高(值为-1 ),并对其他所有) >和ErrorException.

I recommend keeping error_reporting() high (a value of -1) though, and using (as others have suggested) error handling for everything else with set_error_handler() and ErrorException.