2009-05-19 148 views
0

所以:忽略PHP的错误,同时还打印自定义错误消息

@fopen($file); 

忽略任何错误并继续

fopen($file) or die("Unable to retrieve file"); 

忽略错误,杀死程序和打印自定义消息

是有一种简单的方法可以忽略来自函数的错误,打印自定义错误消息而不是杀死程序?

+0

如果你正确配置[display_errors设置](http://www.php.net/manual/en/errorfunc.configuration.php#ini.display-errors),则可以在保持饶@操作兼容性与显示错误(你应该只在开发时 - 如果有的话)。 – hakre 2011-06-03 13:08:34

回答

4

典型:

if (!($fp = @fopen($file))) echo "Unable to retrieve file"; 

或使用方式(其中丢弃文件句柄):

@fopen($file) or printf("Unable to retrieve file"); 
0

而不是死亡你可以抛出一个异常,并以你认为合适的方式集中处理错误处理:-)

2

slosd的方式将无法正常工作。 fopen不会引发异常。您应该手动thow它 我会修改你的第二个的exaple与slosd的结合起来:

try 
{ 
    if (!$f = fopen(...)) throw new Exception('Error opening file!'); 
} 
catch (Exception $e) 
{ 
    echo $e->getMessage() . ' ' . $e->getFile() . ' at line ' . $e->getLine; 
} 
echo ' ... and the code continues ...'; 
1

这是我自己的解决方案。请注意,它需要脚本级别的全局变量或类的静态变量以便于参考。我写它的类风格作为参考,但只要它能找到数组就可以了。

class Controller { 
    static $errors = array(); 
} 

$handle = fopen($file) or array_push(Controller::errors, 
    "File \"{$file}\" could not be opened."); 

// ...print the errors in your view