我正在尝试从正在开发的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 catch的添加使我能够正确捕获404,但这似乎不适用于500或401响应。任何人都可以建议我要去哪里了。
use例外,否则可能需要在它们前面加上``以明确声明FQ类。因此,例如, '\狂饮\ HTTP \异常\ ClientErrorResponseException'