2011-05-17 88 views
4

嘿家伙, 所以我偶尔会在使用file_get_contents时遇到错误,并在我的脚本中使用了一些公平的位。我知道我可以@file_get_contents单独压制的错误,我也可以设置全局错误信息与file_get_contents()的全局错误处理PHP

//error handler function 
function customError($errno) 
    { 
    echo 'Oh No!'; 
    } 

//set error handler 
set_error_handler("customError"); 

但我怎么专门为所有file_get_content的使用错误处理程序?

感谢

回答

3

你可以调用的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. 

只是猜测。如果您的意思不同,请扩展您的问题。 (你不能调用的每个的file_get_contents调用错误处理 - 如果没有发生任何错误)

1

或检查跟踪和处理错误,如果引用者函数的file_get_contents

//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"); 
0

你的错误处理函数需要更全面的那个。 你会这样做:

<?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);} 

?>