guzzle: Uncaught exceptions

I’m trying to catch exceptions in a post request but at the moment no exceptions are being catched. For instance a 404 not found throws the following exception:

Fatal error: Uncaught exception 'GuzzleHttp\Exception\ClientException' with message 'Client error response [url] http://localhost:3000/broken_path/ [status code] 404 [reason phrase] Not Found' in /myuser/path_to_project/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:89 Stack trace: #0 /myuser/path_to_project/vendor/guzzlehttp/guzzle/src/Subscriber/HttpError.php(33): GuzzleHttp\Exception\RequestException::create(Object(GuzzleHttp\Message\Request), Object(GuzzleHttp\Message\Response)) #1 /myuser/path_to_project/vendor/guzzlehttp/guzzle/src/Event/Emitter.php(109): GuzzleHttp\Subscriber\HttpError->onComplete(Object(GuzzleHttp\Event\CompleteEvent), 'complete') #2 /myuser/path_to_project/vendor/guzzlehttp/guzzle/src/RequestFsm.php(203): GuzzleHttp\Event\Emitter->emit('complete', Object(GuzzleHttp\Event\CompleteEvent)) #3 /myuser/path_to_project/vendor/guzzlehttp/guzzle/src/RequestFsm.php(92): GuzzleHttp\RequestFsm->complete(Object(GuzzleHttp\Transaction)) #4 /myuser/path_to_project/vendor/guzzlehttp/guzzle/s in /myuser/path_to_project/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php on line 89

My code that fires the request:

$client  = new Client();
$request = $client->createRequest( 'POST', 'http://localhost:3000/broken_path/' );
$request->getBody()->setField( 'some_field', 'some_value' );

try {
      $response = $client->send( $request );
    } catch (\GuzzleHttp\Exception\ClientException $e) {
      $response = $e->getResponse();
      if ($response && $response->getStatusCode() == 406) {
        // Do something with a 406 response here (as an example).
      }
      else {
        throw $e;
      }
    }

I got the code from this ticket: https://github.com/guzzle/guzzle/issues/664

Guzzle version: “5.1.0”

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Comments: 17 (6 by maintainers)

Most upvoted comments

When catching a ClientException, you know that a response will be present on the exception because the exception was raised due to encountering a 404 response.

This works:

<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
$client  = new Client();
$request = $client->createRequest('POST', 'http://httpbin.org/status/404', [
    'body' => [
        'some_field' => 'some_value'
    ]
]);
try {
    $response = $client->send( $request );
} catch (\GuzzleHttp\Exception\ClientException $e) {
    echo 'Caught response: ' . $e->getResponse()->getStatusCode();
}

Note that you’re checking for 406 responses and getting back 404 responses from your localhost. Because it isn’t a 406 response, you’re re-throwing the exception.