在 PHP 中安全地捕获“允许的内存大小已用尽"错误
我有一个网关脚本,可以将 JSON 返回给客户端.在脚本中,我使用 set_error_handler 来捕获错误并且仍然有一个格式化返回.
I have a gateway script that returns JSON back to the client. In the script I use set_error_handler to catch errors and still have a formatted return.
它受允许的内存大小耗尽"错误的影响,而不是使用诸如 ini_set('memory_limit', '19T'),我只想返回用户应该尝试其他东西,因为它使用了很多内存.
It is subject to 'Allowed memory size exhausted' errors, but rather than increase the memory limit with something like ini_set('memory_limit', '19T'), I just want to return that the user should try something else because it used to much memory.
有什么好的方法可以捕捉到致命错误?
Are there any good ways to catch fatal errors?
推荐答案
正如 this answer 所建议的,您可以使用 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()
.
您仍然需要管理从违规代码生成的输出,无论是通过 @
(shut up) 操作符,还是 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.
您可以查看shutdown函数中的$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
的值),并使用(正如其他人建议的那样) 使用 set_error_handler()
和 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
.
相关文章