Why Do I Get Errors In Guzzle, Despite The Fact That Everything Is Fine With The Curl?

Asked one year ago
Answer 3
Viewed 10531
1

67

While the answers above are good they will not catch network errors. As Mark mentioned, BadResponseException is just a super class for ClientException and ServerException. But RequestException is also a super class of BadResponseException. RequestException will be thrown for not only 400 and 500 errors but network errors and infinite redirects too. So let's say you request the page below but your network is playing up and your catch is only expecting a BadResponseException. Well your application will throw an error.

It's better in this case to expect RequestException and check for a response.

try {  $client->get('http://123123123.com')} catch (RequestException $e) {  // If there are network errors, we need to ensure the application doesn't crash.  // if $e->hasResponse is not null we can attempt to get the message  // Otherwise, we'll just pass a network unavailable message.  if ($e->hasResponse()) {    $exception = (string) $e->getResponse()->getBody();    $exception = json_decode($exception);    return new JsonResponse($exception, $e->getCode());  } else {    return new JsonResponse($e->getMessage(), 503);  }}

Answered one year ago Naveen Ojha
1

While you can handle 4xx or 5xx status codes specifically, in practice it makes sense to catch all exceptions and handle the results accordingly.

The question is also, whether you just want to handle the errors or get the body? I think in most cases it would be sufficient to handle the errors and not get the message body or only get the body in the case of a non-error.

I would look at the documentation to check how your version of Guzzle handles it because this may change: https://docs.guzzlephp.org/en/stable/quickstart.html#exceptions

Also see this page in the official documentation on "Working with errors", which states:

Answered one year ago Naveen Ojha
0

While the answers above are good they will not catch network errors. As Mark mentioned, BadResponseException is just a super class for ClientException and ServerException. But RequestException is also a super class of BadResponseException. RequestException will be thrown for not only 400 and 500 errors but network errors and infinite redirects too. So let's say you request the page below but your network is playing up and your catch is only expecting a BadResponseException. Well your application will throw an error.

It's better in this case to expect RequestException and check for a response.

Answered one year ago Rajesh Kumar