Catching exceptions from Guzzle

前端 未结 8 1770
情歌与酒
情歌与酒 2020-11-30 22:07

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

8条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-30 22:41

    To catch Guzzle errors you can do something like this:

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

    ... but, to be able to "log" or "resend" your request try something like this:

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

    ... or if you want to "stop event propagation" you can overridde event listener (with a higher priority than -255) and simply stop event propagation.

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

    thats a good idea to prevent guzzle errors like:

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

    in your application.

提交回复
热议问题