验证 guzzle 响应的最佳做法

Best practice to verify guzzle response

我想知道检查 guzzle 响应是否正常并避免阻止应用程序的最佳做法是什么。我使用 PHP/Symfony,每次打电话时我都会做以下事情:

try {

    $response = $this->getClient()->request('GET', '/api/rest/contact/' . $email);

} catch (\Exception $e) {

    $logger = $this->get('monolog.logger.myapp');
    $logger->critical('New exception caught while getting user: ' . $e);
    throw new HttpException(406, "Error while getting user.");
}

if(isset($response) && $response->getStatusCode() == 200) {
    return $response->getBody()->getContents();
}

// if it's not 200 or the response is not set, I send a JsonResponse or a flash message to be used in a form for instance:

$this->addFlash('error', $this->get('translator')->trans('form.subscribe.fail', array(), 'messages'));

// or

return new JsonResponse(array('messages' => [0 => $this->get('translator')->trans('form.subscribe.fail', array(), 'messages')]), 400);

编辑以适应收到的答案:

try {

    $response = $this->getClient()->request('GET', '/api/rest/contact/' . $email);

} catch (\Exception $e) {

    $logger = $this->get('monolog.logger.myapp');
    $logger->critical('New exception caught while getting user: ' . $e);

    // the response is not 200 so I send a JsonResponse or a flash message to be used in a form for instance:

    $this->addFlash('error', $this->get('translator')->trans('form.subscribe.fail', array(), 'messages'));

    // or

    return new JsonResponse(array('messages' => [0 => $this->get('translator')->trans('form.subscribe.fail', array(), 'messages')]), 400);
}

return $response->getBody()->getContents();

"OK" 取决于您的端点提供商。即使状态代码 = 200(某些糟糕的 API 会这样做),一些提供程序也可以响应错误。

基本上,如果状态代码发出错误信号(状态代码 >= 400),Guzzle 默认会抛出异常。所以你不需要做额外的检查,只处理异常。

顺便说一句,查看 this answer 了解更多信息。