[英]How can I make Symfony2 ignore Guzzle Client bad response exception in my custom controller?
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語句?
$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代碼,我也可以訪問遠程服務器的響應。
Per Guzzle文檔 :
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解碼響應時檢查錯誤可能也是一個好主意,因為在您獲得的內容中可能會出現意外(例如,格式錯誤,缺少或意外的字段或值等)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.