Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to catch PHP file_get_contents error using try catch block

I am trying to fetch an image using file_get_contents function but it gives an error. To handle the error I am using try catch block but it does not catch the error and fails.

My code:

try {
     $url = 'http://wxdex.ocm/pdd.jpg'; //dummy url
     $file_content = file_get_contents($url);
}
catch(Exception $e) {
     echo 'Error Caught';           
}

Error:

Warning: file_get_contents(): php_network_getaddresses: getaddrinfo failed: No such host is known
Warning: file_get_contents(http://wxdex.ocm/pdd.jpg): failed to open stream: php_network_getaddresses: getaddrinfo failed: No such host is known.

NOTE:: I am able to fetch any other valid image url on remote.

like image 886
D555 Avatar asked Jun 29 '18 06:06

D555


1 Answers

try/catch doesn't work because a warning is not an exception.

You can try this code so you can catch warnings as well.

//set your own error handler before the call
set_error_handler(function ($err_severity, $err_msg, $err_file, $err_line, array $err_context)
{
    throw new ErrorException( $err_msg, 0, $err_severity, $err_file, $err_line );
}, E_WARNING);

try {
    $url = 'http://wxdex.ocm/pdd.jpg';
    $file_content = file_get_contents($url);
} catch (Exception $e) {
    echo 'Error Caught'; 
}

//restore the previous error handler
restore_error_handler();
like image 65
Edison Biba Avatar answered Sep 19 '22 14:09

Edison Biba