我正在尝试从我正在开发的API上运行的一组测试中捕获异常,并且我使用Guzzle来使用API方法.我已经将测试包装在try/catch块中,但它仍然会抛出未处理的异常错误.按照文档中的描述添加事件侦听器似乎没有做任何事情.我需要能够检索具有500,401,400的HTTP代码的响应,实际上任何不是200的响应,因为如果系统不起作用,系统将根据调用的结果设置最合适的代码.
当前的代码示例
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 …Run Code Online (Sandbox Code Playgroud)