file_get_contents 处理错误的好方法

新手上路,请多包涵

我正在尝试错误处理 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);
}

原文由 Hashey100 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 780
2 个回答

尝试使用 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);
?>

原文由 Andrey Volk 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

原文由 m4t1t0 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题