开发者

Global error handling of file_get_contents() PHP

开发者 https://www.devze.com 2023-03-06 22:18 出处:网络
I am occasionally getting errors while using file_get_contents and its used a fair bit in my script. I know I can suppress errors individually with @file_get_contents and that I can set global error m

I am occasionally getting errors while using file_get_contents and its used a fair bit in my script. I know I can suppress errors individually with @file_get_contents and that I can set global error messages with

//error handler function
function customError($errno)
  {
  echo开发者_开发技巧 'Oh No!';
  }

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

But how do I specifically set an error handler for all file_get_content's uses?

Thanks


you may set your custom error_handler before invoking file_get_contents and then use restore_error_handler() function right after file_get_contents. if there is multiple usage of file_get_contents in your code, you may wrap file_get_contents by some custom function.


@ does not really suppress the errors as you've discovered. They still show up in your custom error handler. And to have "suppressed" errors ignored there, you have to first probe for the current error_level:

function customError($errno)
{
   if ( !error_reporting() ) return;

   echo 'Oh No!';
}

// That's what PHPs default error handler does too.

Just guessing. If you meant something different, please extend your question. (You cannot have an error handler invoked for each file_get_contents call - if there didn't occur any error.)


or check the trace and handle error if referer function is 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");


your error handler function would need tobe more comprehensive then that. you would do something like:

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

?>
0

精彩评论

暂无评论...
验证码 换一张
取 消