【问题标题】:Global error handling of file_get_contents() PHPfile_get_contents() PHP 的全局错误处理
【发布时间】:2011-05-17 09:34:35
【问题描述】:
我在使用 file_get_contents 时偶尔会遇到错误,并且在我的脚本中使用了相当多的内容。我知道我可以使用 @file_get_contents 单独抑制错误,并且我可以设置全局错误消息
//error handler function
function customError($errno)
{
echo 'Oh No!';
}
//set error handler
set_error_handler("customError");
但是我如何专门为所有 file_get_content 的使用设置错误处理程序?
谢谢
【问题讨论】:
标签:
php
handler
file-get-contents
【解决方案1】:
您可以在调用 file_get_contents 之前设置您的自定义 error_handler,然后在 file_get_contents 之后使用 restore_error_handler() 函数。如果您的代码中多次使用 file_get_contents,您可以通过一些自定义函数包装 file_get_contents。
【解决方案2】:
@ 并没有真正抑制您发现的错误。它们仍会出现在您的自定义 error handler 中。并且要在那里忽略“抑制”错误,您必须首先探测当前的error_level:
function customError($errno)
{
if ( !error_reporting() ) return;
echo 'Oh No!';
}
// That's what PHPs default error handler does too.
只是猜测。如果您的意思有所不同,请扩展您的问题。 (您不能为 each file_get_contents 调用调用错误处理程序 - 如果没有发生任何错误。)
【解决方案3】:
如果referer函数是file_get_contents,则检查trace并处理错误
//error handler function
function customError($errno)
{
$a = debug_backtrace();
if($a[1]['function'] == 'file_get_contents')
{
echo 'Oh No!';
}
}
//set error handler
set_error_handler("customError");
【解决方案4】:
你的错误处理函数需要更全面。
你会做这样的事情:
<?php
function customError($errno,$errstr){
switch ($errno) {
case E_USER_ERROR:
echo "<b>ERROR</b> $errstr<br />\n";
break;
case E_USER_WARNING:
echo "<b>WARNING</b> $errstr<br />\n";
break;
case E_USER_NOTICE:
echo "<b>NOTICE</b> $errstr<br />\n";
break;
default:
echo "Whoops there was an error in the code, check below for more infomation:<br/>\n";
break;
}
return true;
}
set_error_handler("customError");
$filename = 'somemissingfile.txt';
$file = file_get_contents($filename);
//add the trigger_error after your file_get_contents
if($file===false){trigger_error('Could not get:'.$filename.' - on line 27<br/>',E_USER_ERROR);}
?>