1

I am programming a little application for myself. This application is calling to different websites with the package Guzzle.

However, I want to store every request in my database with the time and the request duration time and the request status code I get. The problem I am facing here right now is that I don't know how to get the http status code when the request fails..

This is my code so far:

$client = $this->getGuzzleClient();
$request = $client->post($url, $headers, $value);
try {
    $response = $request->send();
    return $response->getBody();
}catch (\GuzzleHttp\Exception\RequestException $e){
    dd(array($e, $e->getResponse()));
}

The $e->getResponse() returns null. I also tried to use $e->getStatusCode() or $e->getRequest()->getStatusCode(). Both are not working...

To be absolutely sure the request is valid and I deal with a real exception I call to this website https://httpstat.us/503. This returns a 503 http status code...

So, how can I get the http status code? Do you guys have any idea?

Kind regards and Thank You!

Jan
  • 1,180
  • 3
  • 23
  • 60
  • 1
    Check this https://stackoverflow.com/a/30957410/847950 – namelivia Jan 25 '19 at 09:15
  • `$e->getRequest()->getBody()->getContents()` returns null and `$e->getCode()` returns `0` although the website definitely returns a `503` error. – Jan Jan 25 '19 at 09:19
  • 1
    Try catching a `ServerException` or a `BadResponseException` not a `RequestException` – namelivia Jan 25 '19 at 09:21
  • Why? But what happens if it isn't a `ServerException` or a `BadResponseException`? Then I cannot catch the other exceptions? – Jan Jan 25 '19 at 09:23
  • 1
    If you catch a `ServerException` you are catching a 5xx, if the code execution enters there Guzzle has received a 5xx. If you catch a `RequestException` that includes network errors too. If the code execution enters on the `RequestException` but does not on the `ServerException` means that for Guzzle is not a 5xx error but a network error. – namelivia Jan 25 '19 at 09:25
  • Thanks - working now! – Jan Jan 25 '19 at 09:29
  • I'm posting it as the answer so we can mark the question as solved. Thanks. – namelivia Jan 25 '19 at 09:36

2 Answers2

2

If you catch a ServerException you are catching a 5xx, if the code execution enters there Guzzle has received a 5xx. If you catch a RequestException that includes network errors too. If the code execution enters on the RequestException but does not on the ServerException means that for Guzzle is not a 5xx error but a network error.

namelivia
  • 2,657
  • 1
  • 21
  • 24
0

$errorstatuscode=$exception->status;

// to get error code from Excetion Object