忽略PHP错误,同时仍打印自定义错误消息

忽略PHP错误,同时仍打印自定义错误消息,php,error-handling,Php,Error Handling,因此: 忽略任何错误并继续 @fopen($file); 忽略错误,终止程序并打印自定义消息 有没有一种简单的方法可以忽略函数中的错误、打印自定义错误消息而不终止程序?通常: fopen($file) or die("Unable to retrieve file"); 或者使用您的方式(放弃文件句柄): 使用例外: @fopen($file) or printf("Unable to retrieve file"); 有关详细信息,请访问,您可以抛出异常并以您认为合适的方式集中执行错误处

因此:

忽略任何错误并继续

@fopen($file);
忽略错误,终止程序并打印自定义消息

有没有一种简单的方法可以忽略函数中的错误、打印自定义错误消息而不终止程序?

通常:

fopen($file) or die("Unable to retrieve file");
或者使用您的方式(放弃文件句柄):

使用例外:

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

有关详细信息,请访问,您可以抛出异常并以您认为合适的方式集中执行错误处理:-)

slosd的方式不起作用fopen不会引发异常。你应该手动去做 我将修改您的第二个示例,并将其与slosd结合起来:

try {
   fopen($file);
} catch(Exception $e) {
   /* whatever you want to do in case of an error */
}

这是我自己的解决办法。请注意,它需要一个脚本级别的全局变量或一个类的静态变量,以便于引用。我以类风格编写它以供参考,但只要它能找到数组就可以了

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 ...';

fopen不会引发异常。一旦您添加了适当的处理程序,它就会引发异常:如果您正确配置,您可以在保持与显示错误的兼容性的同时释放@operator(您应该只在开发时才这样做-如果有的话)。
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 ...';
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