验证guzzle响应的最佳做法

时间:2016-08-23 13:48:33

标签: php rest symfony http guzzle

我想知道检查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();

1 个答案:

答案 0 :(得分:1)

" OK"取决于你的终点'供应商。即使状态代码= 200(某些crapy API执行此操作),某些提供程序也可以响应错误。

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

BTW,请查看this answer了解更多信息。