【问题标题】:try catch not working in PHP尝试捕获在 PHP 中不起作用
【发布时间】:2016-12-14 09:01:59
【问题描述】:

我有以下代码,旨在在 try catch 中运行一些代码。但是,当file_get_content 失败时,它仍然不会进入catch 函数,而是继续运行并显示更多错误(例如property_exists,因为$weatherJson 未定义。

   try{
        $weatherJson = file_get_contents("http://api.someApi?lat={$this->request->getParam("lon")}&lon={$this->request->getParam("lon")}&appid=abcdefg");
        $weatherJson = json_decode($weatherJson);
        if (property_exists($weatherJson, 'list')) {
            $result->weather = $weatherJson->list[0]->weather[0]->main;
            $result->timeStamp = $weatherJson->list[0]->dt_txt;
            return $result;
        } else {
            return "no results found";
        }
    } catch(\Exception $e) {
        echo "something is wrong";

    }

【问题讨论】:

  • file_get_contents 不会抛出异常
  • try...catch 仅在引发异常时有效。 file_get_contents 失败时不会抛出异常。来自手册@return string The function returns the read data or false on failure.
  • 你应该考虑阅读手册
  • 手册还指出“如果找不到文件名、maxlength 小于零或在流中查找指定偏移量失败,则会生成 E_WARNING 级别错误” 所以你可能会得到false 的结果一个警告,但仍然没有例外。

标签: php exception exception-handling


【解决方案1】:

函数file_get_contents 不会抛出异常,它在失败时返回false。如果返回 false,您可以调整代码以自己抛出异常。

try {
    $weatherJson = @file_get_contents("http://api.someApi?lat={$this->request->getParam("lon")}&lon={$this->request->getParam("lon")}&appid=abcdefg");
    if (!$weatherJson) {
        throw new \Exception;
    }

    $weatherJson = json_decode($weatherJson);
    if (property_exists($weatherJson, 'list')) {
        $result->weather = $weatherJson->list[0]->weather[0]->main;
        $result->timeStamp = $weatherJson->list[0]->dt_txt;

        return $result;
    } else {
        return "no results found";
    }
} catch(\Exception $e) {
    echo "something is wrong";
}

【讨论】:

  • 谢谢,但即使我添加了该异常,我仍然收到警告:file_get_contents with a 502 Bad Gateway,因为我故意在该 API 中提供了错误的参数.. 有没有办法隐藏那个警告?
  • 是的,您可以通过将@ 符号放在file_get_contents 之前来抑制警告,这样它就变成了@file_get_contents('...');。查看我的更新答案
【解决方案2】:

file_get_contents 不会抛出异常。

失败时,file_get_contents() 将返回 FALSE。

【讨论】:

    【解决方案3】:
    try{
            $weatherJson = file_get_contents("http://api.someApi?lat={$this->request->getParam("lon")}&lon={$this->request->getParam("lon")}&appid=abcdefg");
            $weatherJson = json_decode($weatherJson);
            if (property_exists($weatherJson, 'list')) {
                $result->weather = $weatherJson->list[0]->weather[0]->main;
                $result->timeStamp = $weatherJson->list[0]->dt_txt;
                return $result;
            } else {
                return "no results found";
            }
        } catch(\Exception $e) {
            echo "something is wrong";
    
        }
    

    在你的捕获中有\,删除它

    【讨论】:

    • 实际上,由于我在项目中的文件层次结构,我确实需要那个反斜杠。
    • 应该为你的 $weatherJson 添加验证,不需要 try catch then if($weatherJson)
    猜你喜欢
    • 2018-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-28
    • 1970-01-01
    • 2018-03-25
    • 1970-01-01
    相关资源
    最近更新 更多