如何在我的自定义控制器中使Symfony2忽略Guzzle Client错误响应异常?

时间:2014-07-30 19:47:17

标签: php symfony guzzle symfony-2.5

   function order_confirmationAction($order,$token) { 

        $client = new \GuzzleHttp\Client();
        $answer  = $client->post("http://www.fullcommerce.com/rest/public/Qtyresponse",
                    array('body' => $order)
        );

        $answer  = json_decode($answer); 

        if ($answer->status=="ACK") {
            return $this->render('AcmeDapiBundle:Orders:ack.html.twig', array(
            'message'   => $answer->message,
        ));
        } else throw new \Symfony\Component\HttpKernel\Exception\HttpException(500, $answer->message);
}

如果$ client-> post()响应状态代码为"错误500" Symfony停止脚本执行并在json解码之前抛出新异常。 如何强制Symfony忽略$ client-> post()错误响应并执行到最后一个if语句?

2 个答案:

答案 0 :(得分:3)

            $client = new \GuzzleHttp\Client();
            try {
                $answer  = $client->post("http://www.fullcommerce.com/rest/public/Qtyresponse",
                        array('body' => $serialized_order)
                );
            }
            catch (\GuzzleHttp\Exception\ServerException $e) {

                if ($e->hasResponse()) {
                    $m = $e->getResponse()->json();
                    throw new \Symfony\Component\HttpKernel\Exception\HttpException(500, $m['result']['message']);
                }

            }
我解决了这个问题。这样,即使它返回错误500代码,我也可以访问远程服务器的响应。

答案 1 :(得分:0)

Guzzle documentation

  

Guzzle会针对传输过程中发生的错误抛出异常。

具体来说,如果API以500 HTTP错误响应,您不应期望其内容为JSON,并且您不想解析它,因此您最好不要从那里抛出异常(或通知用户出现了问题)。我建议尝试一下:

function order_confirmationAction($order, $token) { 
    $client = new \GuzzleHttp\Client();
    try {
        $answer  = $client->post("http://www.fullcommerce.com/rest/public/Qtyresponse",
            array('body' => $order)
        );
    }
    catch (Exception $e) {
        throw new \Symfony\Component\HttpKernel\Exception\HttpException(500, $e->getMessage());
    }

    $answer  = json_decode($answer); 

    if ($answer->status=="ACK") {
        return $this->render('AcmeDapiBundle:Orders:ack.html.twig', array(
            'message'   => $answer->message,
        ));
    } else {
        throw new \Symfony\Component\HttpKernel\Exception\HttpException(500, $answer->message);
    }
}

在JSON解码响应时检查错误可能也是一个好主意,因为您可能会遇到意外的内容(例如错误的格式,缺失或意外的字段或值等)。 )。