I am trying to catch the exceptions from the test suite that I run on the API that I am developing, and I use Guzzle to use the API methods. I have tests wrapped in a try / catch block, but it still throws unhandled exception errors. Adding an event listener as described in their docs doesn't seem to do anything. I need to get answers containing HTTP codes 500, 401, 400, in fact everything is not 200, because the system will set the most suitable code based on the result of the call if it does not work.
Current code example
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; }
Even with a specific catch block for the selected exception type, I still return
Fatal error: Uncaught exception 'Guzzle\Http\Exception\ClientErrorResponseException' with message 'Client error response [status code] 401 [reason phrase] Unauthorized [url]
and all execution on the page stops, as you would expect. Adding a BadResponseException capture allowed me to catch 404s correctly, but this does not seem to work for 500 or 401 responses. Can anyone suggest where I am wrong, please.
api php functional-testing guzzle
Eric Harth Jul 15 '13 at 15:44 2013-07-15 15:44
source share