我想從我正在開發的API上運行的一組測試中捕獲異常,並使用Guzzle來使用API方法。我已經將測試包裝在try/catch塊中,但它仍然拋出未處理的異常錯誤。按照他們的文檔中所述添加事件偵聽器似乎沒有任何作用。我需要能夠檢索HTTP代碼爲500,401,400的響應,實際上不是200的響應,因爲如果系統不工作,系統將根據通話結果設置最合適的代碼。從Guzzle捕捉異常
當前的代碼示例
foreach($tests as $test){
$client = new Client($api_url);
$client->getEventDispatcher()->addListener('request.error', function(Event $event) {
if ($event['response']->getStatusCode() == 401) {
$newResponse = new Response($event['response']->getStatusCode());
$event['response'] = $newResponse;
$event->stopPropagation();
}
});
try {
$client->setDefaultOption('query', $query_string);
$request = $client->get($api_version . $test['method'], array(), isset($test['query'])?$test['query']:array());
// Do something with Guzzle.
$response = $request->send();
displayTest($request, $response);
}
catch (Guzzle\Http\Exception\ClientErrorResponseException $e) {
$req = $e->getRequest();
$resp =$e->getResponse();
displayTest($req,$resp);
}
catch (Guzzle\Http\Exception\ServerErrorResponseException $e) {
$req = $e->getRequest();
$resp =$e->getResponse();
displayTest($req,$resp);
}
catch (Guzzle\Http\Exception\BadResponseException $e) {
$req = $e->getRequest();
$resp =$e->getResponse();
displayTest($req,$resp);
}
catch(Exception $e){
echo "AGH!";
}
unset($client);
$client=null;
}
即使與拋出的異常類型的特定catch塊我仍然找回
Fatal error: Uncaught exception 'Guzzle\Http\Exception\ClientErrorResponseException' with message 'Client error response [status code] 401 [reason phrase] Unauthorized [url]
和頁面上的所有執行停止,正如你所期望。 BadResponseException catch的添加允許我正確捕獲404,但這似乎不適用於500或401響應。任何人都可以建議我哪裏錯了請。
此代碼是否在命名空間下?如果是這樣,除非你使用例外,你可能需要用'\'來前綴它們來顯式聲明FQ類。因此,例如'\ Guzzle \ Http \ Exception \ ClientErrorResponseException' –