1try {
2 /**
3 * We use Guzzle to make an HTTP request somewhere in the
4 * following theMethodMayThrowException().
5 */
6 $result = theMethodMayThrowException();
7} catch (\GuzzleHttp\Exception\RequestException $e) {
8 /**
9 * Here we actually catch the instance of GuzzleHttp\Psr7\Response
10 * (find it in ./vendor/guzzlehttp/psr7/src/Response.php) with all
11 * its own and its 'Message' trait's methods. See more explanations below.
12 *
13 * So you can have: HTTP status code, message, headers and body.
14 * Just check the exception object has the response before.
15 */
16 if ($e->hasResponse()) {
17 $response = $e->getResponse();
18 var_dump($response->getStatusCode()); // HTTP status code;
19 var_dump($response->getReasonPhrase()); // Response message;
20 var_dump((string) $response->getBody()); // Body, normally it is JSON;
21 var_dump(json_decode((string) $response->getBody())); // Body as the decoded JSON;
22 var_dump($response->getHeaders()); // Headers array;
23 var_dump($response->hasHeader('Content-Type')); // Is the header presented?
24 var_dump($response->getHeader('Content-Type')[0]); // Concrete header value;
25 }
26}
27// process $result etc. ...
28
1use GuzzleHttp\Client;
2use GuzzleHttp\Exception\RequestException;
3use GuzzleHttp\Exception\ConnectException;
4
5$client = new Client();
6
7try{
8 $response = $client->request('GET', 'http://github.com');
9}
10catch (ConnectException $e) {
11 // Connection exceptions are not caught by RequestException
12 echo "Internet, DNS, or other connection error\n";
13 die;
14}
15catch (RequestException $e) {
16 echo "Request Exception\n";
17 die;
18}
19// deal with your $reponse here