处理JSON API响应(无论是否返回错误,返回200)的最佳方法是什么

问题描述 投票:0回答:1

因此,我向一些不可靠的来源(我无法控制)发出Guzzle HTTP请求。

响应返回2之一:

具有以下错误的200状态代码:

{
    "error": "Data source error, please try again"
}

和200个状态代码以及以下响应数据:

{
    "products": {
        "income": "Income Protection",
        "car": "Car Insurance"
    }
}

这是我通过Guzzle发出请求的方式:

        try {

            $client = new Client(array(
                'curl'   => array( CURLOPT_SSL_VERIFYPEER => false ),
                'verify' => false
            ));
            $res = $client->request($method, self::URI . $url, [
                $params
            ]);

            return $res->getBody();
        } catch (ClientException $e) {
            echo Psr7\str($e->getRequest());
            echo Psr7\str($e->getResponse());
        }

因此,当我收到上面的错误响应时,它将永远不会到达代码的catch部分,因为它会返回成功的200状态代码。

什么是处理此问题的最佳方法,以便我可以适当地返回错误响应?

php json http error-handling guzzle
1个回答
2
投票

$result = json_decode($res);

if(!isset($result->error))...

© www.soinside.com 2019 - 2024. All rights reserved.