Eri*_*ric 69 php api functional-testing guzzle
我正在尝试从我正在开发的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 =$e->getResponse();
displayTest($req,$resp);
}
catch( Exception $e){
echo "AGH!";
}
unset($client);
$client=null;
}
Run Code Online (Sandbox Code Playgroud)
即使使用抛出异常类型的特定catch块,我仍然会回来
Fatal error: Uncaught exception 'Guzzle\Http\Exception\ClientErrorResponseException' with message 'Client error response [status code] 401 [reason phrase] Unauthorized [url]
Run Code Online (Sandbox Code Playgroud)
正如您所期望的那样,页面上的所有执行都会停止.添加BadResponseException捕获允许我正确捕获404,但这似乎不适用于500或401响应.任何人都可以建议我哪里出错了.
Tre*_*her 118
根据您的项目,可能需要禁用guzzle异常.有时编码规则不允许流控制的异常.你可以像这样禁用Guzzle 3的例外:
$client = new \Guzzle\Http\Client($httpBase, array(
'request.options' => array(
'exceptions' => false,
)
));
Run Code Online (Sandbox Code Playgroud)
这不会禁用诸如超时之类的卷曲异常,但现在您可以轻松获取每个状态代码:
$request = $client->get($uri);
$response = $request->send();
$statuscode = $response->getStatusCode();
Run Code Online (Sandbox Code Playgroud)
要检查一下,如果你有一个有效的代码,你可以使用这样的东西:
if ($statuscode > 300) {
// Do some error handling
}
Run Code Online (Sandbox Code Playgroud)
...或更好地处理所有预期的代码:
if (200 === $statuscode) {
// Do something
}
elseif (304 === $statuscode) {
// Nothing to do
}
elseif (404 === $statuscode) {
// Clean up DB or something like this
}
else {
throw new MyException("Invalid response from api...");
}
Run Code Online (Sandbox Code Playgroud)
对于Guzzle 5.3
$client = new \GuzzleHttp\Client(['defaults' => [ 'exceptions' => false ]] );
Run Code Online (Sandbox Code Playgroud)
感谢@mika
对于Guzzle 6
$client = new \GuzzleHttp\Client(['http_errors' => false]);
Run Code Online (Sandbox Code Playgroud)
Dad*_*ado 45
要捕获Guzzle错误,您可以执行以下操作:
try {
$response = $client->get('/not_found.xml')->send();
} catch (Guzzle\Http\Exception\BadResponseException $e) {
echo 'Uh oh! ' . $e->getMessage();
}
Run Code Online (Sandbox Code Playgroud)
...但是,为了能够"记录"或"重新发送"您的请求,请尝试以下方法:
// Add custom error handling to any request created by this client
$client->getEventDispatcher()->addListener(
'request.error',
function(Event $event) {
//write log here ...
if ($event['response']->getStatusCode() == 401) {
// create new token and resend your request...
$newRequest = $event['request']->clone();
$newRequest->setHeader('X-Auth-Header', MyApplication::getNewAuthToken());
$newResponse = $newRequest->send();
// Set the response object of the request without firing more events
$event['response'] = $newResponse;
// You can also change the response and fire the normal chain of
// events by calling $event['request']->setResponse($newResponse);
// Stop other events from firing when you override 401 responses
$event->stopPropagation();
}
});
Run Code Online (Sandbox Code Playgroud)
...或者如果你想"停止事件传播",你可以覆盖事件监听器(优先级高于-255)并简单地停止事件传播.
$client->getEventDispatcher()->addListener('request.error', function(Event $event) {
if ($event['response']->getStatusCode() != 200) {
// Stop other events from firing when you get stytus-code != 200
$event->stopPropagation();
}
});
Run Code Online (Sandbox Code Playgroud)
这是一个好主意,以防止guzzle错误,如:
request.CRITICAL: Uncaught PHP Exception Guzzle\Http\Exception\ClientErrorResponseException: "Client error response
Run Code Online (Sandbox Code Playgroud)
在你的申请中.
dmm*_*mmd 29
在我的情况下,我扔Exception了一个命名空间文件,所以php试图捕获My\Namespace\Exception因此根本没有捕获任何异常.
值得检查是否catch (Exception $e)找到合适的Exception班级.
试试catch (\Exception $e)(在\那里),看看它是否有效.
小智 11
您需要使用http_errors => false添加额外参数
$request = $client->get($url, ['http_errors' => false]);
Run Code Online (Sandbox Code Playgroud)
bhu*_*cho 11
我想更新 Psr-7 Guzzle、Guzzle7 和 HTTPClient 中异常处理的答案(围绕 Laravel 提供的 Guzzle HTTP 客户端的富有表现力的最小 API)。
使用 RequestException, RequestException 捕获传输请求时可能引发的任何异常。
try{
$client = new \GuzzleHttp\Client(['headers' => ['Authorization' => 'Bearer ' . $token]]);
$guzzleResponse = $client->get('/foobar');
// or can use
// $guzzleResponse = $client->request('GET', '/foobar')
if ($guzzleResponse->getStatusCode() == 200) {
$response = json_decode($guzzleResponse->getBody(),true);
//perform your action with $response
}
}
catch(\GuzzleHttp\Exception\RequestException $e){
// you can catch here 400 response errors and 500 response errors
// You can either use logs here use Illuminate\Support\Facades\Log;
$error['error'] = $e->getMessage();
$error['request'] = $e->getRequest();
if($e->hasResponse()){
if ($e->getResponse()->getStatusCode() == '400'){
$error['response'] = $e->getResponse();
}
}
Log::error('Error occurred in get request.', ['error' => $error]);
}catch(Exception $e){
//other errors
}
Run Code Online (Sandbox Code Playgroud)
use GuzzleHttp\Psr7;
use GuzzleHttp\Exception\RequestException;
try {
$client->request('GET', '/foo');
} catch (RequestException $e) {
$error['error'] = $e->getMessage();
$error['request'] = Psr7\Message::toString($e->getRequest());
if ($e->hasResponse()) {
$error['response'] = Psr7\Message::toString($e->getResponse());
}
Log::error('Error occurred in get request.', ['error' => $error]);
}
Run Code Online (Sandbox Code Playgroud)
use Illuminate\Support\Facades\Http;
try{
$response = Http::get('http://api.foo.com');
if($response->successful()){
$reply = $response->json();
}
if($response->failed()){
if($response->clientError()){
//catch all 400 exceptions
Log::debug('client Error occurred in get request.');
$response->throw();
}
if($response->serverError()){
//catch all 500 exceptions
Log::debug('server Error occurred in get request.');
$response->throw();
}
}
}catch(Exception $e){
//catch the exception here
}
Run Code Online (Sandbox Code Playgroud)
旧问题,但Guzzle在异常对象中添加了响应.所以一个简单的try-catch GuzzleHttp\Exception\ClientException然后使用getResponse该异常来查看400级错误并从那里继续.
| 归档时间: |
|
| 查看次数: |
106752 次 |
| 最近记录: |