我正在查询一个API,但有时在随机执行脚本后,API会发送503、400等错误。
我试图捕获它,但是无论如何尝试,我的脚本都将停止,并且我需要继续手动检查脚本是否停止。
有没有办法捕获在Try块中发生的每个错误?
PHP Fatal error: Uncaught Exception: Client error:
GET http://xxxxxxxxxx
resulted in a400 Bad Request
response:
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.
}
最佳答案
使用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.
}
关于php - 如何 try catch 并继续php中的脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40235946/