【问题标题】:What is the best way to handle a JSON API response which returns 200 regardless of error or not处理返回 200 的 JSON API 响应的最佳方法是什么,无论是否有错误
【发布时间】:2020-01-30 18:43:16
【问题描述】:

所以我向一些不可靠的来源(我无法控制)发出 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 状态代码。

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

【问题讨论】:

  • 您不能只检查响应是否在数据的根目录中具有error 值,并执行相同的操作,就好像它引发了其他形式的错误一样。
  • 在响应正文中检查error 或者使用complete event 拦截

标签: php json http error-handling guzzle


【解决方案1】:

$result = json_decode($res);

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-24
    • 1970-01-01
    • 2015-06-12
    • 2017-11-13
    • 2017-12-26
    • 2019-10-25
    • 1970-01-01
    相关资源
    最近更新 更多