我正在查询API,但有时候API会在随机执行脚本后发送503,400等错误。
我试图抓住它,但无论我如何尝试,我的脚本都停止了,如果脚本停止,我需要继续手动检查。
有没有办法捕获Try块中发生的每个错误?
PHP致命错误:未捕获异常:客户端错误:
GET http://xxxxxxxxxx
导致400 Bad Request
响应:
while ($x <= 5000) {
try {
sleep(2);
$formattedResponse = $apaiIO - > runOperation($lookup);
$xml = simplexml_load_string($formattedResponse);
} catch (\GuzzleHttp\ Exception\ ServerException $e) {
$code = $e - > getResponse() - > getStatusCode();
echo "<strong>Error:</strong> ".$e - > getResponse() - > getReasonPhrase().
" <strong>Code:</strong> ".$code.
"<br>";
switch ($code) {
// throttle request/service unavailable;
case 503:
sleep(2);
default:
sleep(2);
throw new Exception($e - > getResponse() - > getReasonPhrase(), $code);
}
} catch (\Exception $e) {
sleep(2);
//Last error was thrown by this line.
throw new Exception($e - > getMessage(), $e - > getCode());
}
//do script stuff here.
}
答案 0 :(得分:0)
使用continue并将整个try-catch保留在另一个循环中不应该再破坏脚本。
$success=false;
$cattempt=0;// current attempt;
while($cattempt<=2){
try{
sleep(2);
$xml = simplexml_load_string($formattedResponse);
$success=true;
}catch (\GuzzleHttp\Exception\ServerException $e) {
$code=$e->getResponse()->getStatusCode();
echo "<strong>Error:</strong> ".$e->getResponse()->getReasonPhrase()." <strong>Code:</strong> ".$code."<br>";
switch($code){
// throttle request/service unavailable;
case 503:
sleep(2);
$cattempt++; // will try again.
break; // break from switch
default:
// sleep(2);
// $cattempt++;
break 2; // break from swtich and while loop
// throw new Exception($e->getResponse()->getReasonPhrase(),$code);
}
}
catch (\Exception $e) {
echo "<strong>Error:</strong> ".$e->getMessage()." <strong>Code:</strong> ".$e->getCode()."<br>";
sleep(2);
break; // break from while;
// throw new Exception($e->getMessage(),$e->getCode());
}
if($success) break;
}
if(!$success){
continue; // go to next ASIN.
}