14

我正在尝试错误处理 file_get_contents 方法,因此即使用户输入了错误的网站,它也会回显错误消息而不是不专业的

警告:file_get_contents(sidiowdiowjdiso):打开流失败:第 6 行的 C:\xampp\htdocs\test.php 中没有这样的文件或目录

我想如果我尝试并抓住它,它将能够抓住错误,但这不起作用。

try  
{  
$json = file_get_contents("sidiowdiowjdiso", true); //getting the file content
}  
catch (Exception $e)  
{  
 throw new Exception( 'Something really gone wrong', 0, $e);  
}  
4

4 回答 4

15

尝试使用curl_error而不是 file_get_contents 的 cURL:

<?php
// Create a curl handle to a non-existing location
$ch = curl_init('http://404.php.net/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$json = '';
if( ($json = curl_exec($ch) ) === false)
{
    echo 'Curl error: ' . curl_error($ch);
}
else
{
    echo 'Operation completed without any errors';
}

// Close handle
curl_close($ch);
?>
于 2013-04-21T12:04:22.337 回答
9

file_get_contents不要错误抛出异常,而是返回false,因此您可以检查返回值是否为false:

$json = file_get_contents("sidiowdiowjdiso", true);
if ($json === false) {
    //There is an error opening the file
}

这样你仍然会收到警告,如果你想删除它,你需要@file_get_contents. (这被认为是一种不好的做法)

$json = @file_get_contents("sidiowdiowjdiso", true);
于 2013-04-21T12:00:48.080 回答
5

You could do any of the following:

Set a global error handler (that will handle WARNINGs as well), for all of your unhandled exceptions: http://php.net/manual/en/function.set-error-handler.php

Or by checking the return value of the file_get_contents function (with the === operator, as it will return boolean false on failure), and then manage the error message accordingly, and disable the error reporting on the function by prepending a "@" like so:

$json = @file_get_contents("file", true);
if($json === false) {
// error handling
} else {
// do something with $json
}
于 2013-04-21T12:07:05.570 回答
0

作为您的问题的解决方案,请尝试执行以下代码片段

 try  
{  
  $json = @file_get_contents("sidiowdiowjdiso", true); //getting the file content
  if($json==false)
  {
     throw new Exception( 'Something really gone wrong');  
  }
}  
catch (Exception $e)  
{  
  echo $e->getMessage();  
}  
于 2013-04-21T12:18:12.930 回答