【发布时间】:2013-07-13 13:20:51
【问题描述】:
我正在尝试从我正在开发的 API 上运行的一组测试中捕获异常,并且我正在使用 Guzzle 来使用 API 方法。我已经将测试包装在 try/catch 块中,但它仍然抛出未处理的异常错误。如他们的文档中所述添加事件侦听器似乎没有任何作用。我需要能够检索 HTTP 代码为 500、401、400 的响应,实际上任何不是 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 =$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 捕获的添加使我能够正确捕获 404,但这似乎不适用于 500 或 401 响应。谁能建议我哪里出错了。
【问题讨论】:
-
这段代码是否在命名空间下?如果是这样,除非您
useing 异常,否则您可能需要在它们前面加上 `` 以明确声明 FQ 类。因此,例如,'\Guzzle\Http\Exception\ClientErrorResponseException'
标签: php api functional-testing guzzle