Jan
Jan

Reputation: 582

Laravel 5: Guzzle -> getStatusCode on Exception?

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!

Upvotes: 1

Views: 4877

Answers (2)

Harish Gendre
Harish Gendre

Reputation: 21

$errorstatuscode=$exception->status;

// to get error code from Excetion Object

Upvotes: 0

namelivia
namelivia

Reputation: 2735

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.

Upvotes: 2

Related Questions