Skip to content
Advertisement

Catching exceptions from Guzzle

I’m trying to catch exceptions from a set of tests I’m running on an API I’m developing and I’m using Guzzle to consume the API methods. I’ve got the tests wrapped in a try/catch block but it is still throwing unhandled exception errors. Adding an event listener as described in their docs doesn’t seem to do anything. I need to be able to retrieve the responses that have HTTP codes of 500, 401, 400, in fact anything that isn’t 200 as the system will set the most appropriate code based on the result of the call if it didn’t 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 (GuzzleHttpExceptionClientErrorResponseException $e) {

            $req = $e->getRequest();
            $resp =$e->getResponse();
            displayTest($req,$resp);
        }
        catch (GuzzleHttpExceptionServerErrorResponseException $e) {

            $req = $e->getRequest();
            $resp =$e->getResponse();
            displayTest($req,$resp);
        }
        catch (GuzzleHttpExceptionBadResponseException $e) {

            $req = $e->getRequest();
            $resp =$e->getResponse();
            displayTest($req,$resp);
        }
        catch( Exception $e){
            echo "AGH!";
        }

        unset($client);
        $client=null;

    }

Even with the specific catch block for the thrown exception type I am still getting back

Fatal error: Uncaught exception 'GuzzleHttpExceptionClientErrorResponseException' with message 'Client error response [status code] 401 [reason phrase] Unauthorized [url]

and all execution on the page stops, as you’d expect. The addition of the BadResponseException catch allowed me to catch 404s correctly, but this doesn’t seem to work for 500 or 401 responses. Can anyone suggest where I am going wrong please.

Advertisement

Answer

If the Exception is being thrown in that try block then at worst case scenario Exception should be catching anything uncaught.

Consider that the first part of the test is throwing the Exception and wrap that in the try block as well.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement