93

我正在尝试从我正在开发的 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 响应。谁能建议我哪里出错了。

4

9 回答 9

156

根据您的项目,可能需要禁用 guzzle 异常。有时编码规则不允许流控制例外。您可以像这样禁用Guzzle 3 的异常:

$client = new \Guzzle\Http\Client($httpBase, array(
  'request.options' => array(
     'exceptions' => false,
   )
));

这不会为超时等原因禁用 curl 异常,但现在您可以轻松获取每个状态代码:

$request = $client->get($uri);
$response = $request->send();
$statuscode = $response->getStatusCode();

要检查,如果你有一个有效的代码,你可以使用这样的东西:

if ($statuscode > 300) {
  // Do some error handling
}

...或更好地处理所有预期的代码:

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...");
}

对于 Guzzle 5.3

$client = new \GuzzleHttp\Client(['defaults' => [ 'exceptions' => false ]] );

感谢@mika

狂饮 6

$client = new \GuzzleHttp\Client(['http_errors' => false]);
于 2015-02-09T18:42:40.307 回答
47

要捕获 Guzzle 错误,您可以执行以下操作:

try {
    $response = $client->get('/not_found.xml')->send();
} catch (Guzzle\Http\Exception\BadResponseException $e) {
    echo 'Uh oh! ' . $e->getMessage();
}

...但是,为了能够“记录”或“重新发送”您的请求,请尝试以下操作:

// 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();
        }

});

...或者如果您想“停止事件传播”,您可以覆盖事件侦听器(优先级高于 -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();
    }
});

这是防止诸如以下错误的好主意:

request.CRITICAL: Uncaught PHP Exception Guzzle\Http\Exception\ClientErrorResponseException: "Client error response

在您的应用程序中。

于 2013-09-25T14:11:38.263 回答
35

在我的例子中,我抛出Exception了一个命名空间文件,所以 php 试图捕捉,My\Namespace\Exception因此根本没有捕捉到任何异常。

值得检查是否catch (Exception $e)找到了正确的Exception课程。

只需尝试catch (\Exception $e)(在\那里),看看它是否有效。

于 2017-02-16T16:59:11.507 回答
20

如果在该try块中抛出异常,那么在最坏的情况下Exception应该捕获任何未捕获的东西。

考虑到测试的第一部分是抛出异常并将其包装在try块中。

于 2013-07-15T15:51:26.560 回答
14

您需要使用 http_errors => false 添加一个额外的参数

$request = $client->get($url, ['http_errors' => false]);
于 2015-09-14T07:19:31.957 回答
6

我想更新 Psr-7 Guzzle、Guzzle7 和 HTTPClient 中异常处理的答案(富有表现力,围绕 laravel 提供的 Guzzle HTTP 客户端的最小 API)。

Guzzle7(同样适用于 Guzzle 6)

使用 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 
}

Psr7 狂饮

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]);
}

对于 HTTPClient

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
 }

于 2020-10-30T06:27:31.110 回答
5

老问题,但 Guzzle 在异常对象中添加了响应。所以一个简单的 try-catch onGuzzleHttp\Exception\ClientException然后使用getResponse那个异常来查看什么 400 级错误并从那里继续。

于 2016-09-22T19:52:33.163 回答
2

GuzzleHttp\Exception\BadResponseException正如@dado 建议的那样,我正在捕捉。但是有一天,GuzzleHttp\Exception\ConnectException当域的 DNS 不可用时,我得到了。所以我的建议是 - 抓住GuzzleHttp\Exception\ConnectExceptionDNS 错误也是安全的。

于 2016-08-01T08:35:50.697 回答
1

如果您使用的是最新版本,例如 6^ 并且您有 JSON 参数,则可以将'http_errors' => falseJSON 与数组一起添加到数组中,如下所示在此处输入图像描述

我一直在寻找这样做的方法,即在其中使用我的 JSON,但找不到直接的答案。

于 2021-05-21T09:45:57.363 回答