【问题标题】:How to try-catch and continue the script in php如何尝试捕获并继续 php 中的脚本
【发布时间】:2024-01-22 10:15:01
【问题描述】:

我正在查询一个 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.
}

【问题讨论】:

  • 好吧,你正在捕捉异常(可能),但随后你在每种情况下都抛出另一个......
  • 是的,感谢您指出问题

标签: php error-handling try-catch


【解决方案1】:

使用 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.
    }

【讨论】:

    最近更新 更多