問題描述
我有一個網關腳本,可以將 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
.
這篇關于在 PHP 中安全地捕獲“允許的內存大小已用盡"錯誤的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!