我有以下代码用于在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";
}
答案 0 :(得分:0)
file_get_contents不会抛出异常。
失败时,file_get_contents()将返回FALSE。
答案 1 :(得分:0)
函数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";
}
答案 2 :(得分:-1)
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";
}
你的捕获中有\删除它