1

I'm using Guzzle to push some data to an API using the following:

$total_price = round($total_price * 100, 0);
$client = new \GuzzleHttp\Client();
$callback = $client->request('GET', 'https://exaple.com/subscription.js', [
'query' => [
        'aid' => 'c-a-totm-uk',
        'tid' => $order_id,
        'subid' => $reference,
        'rvn' => $total_price,
        'cid' => $customer_id,
    ]
]);
$status = $callback->getStatusCode();

It's not handling the errors/exceptions at the moment.

I've been looking at this question https://stackoverflow.com/a/28416973/609630 but am I right in saying with failures it will cause a fatal error before it hits the following code?

if (404 === $statuscode) {
 // Clean up DB or something like this
} else {
 throw new MyException("Invalid response from api...");
}

How can I handle it properly without causing a fatal error? I'd like to record what any errors are (I can do the recording part, just need to output the error).

Rob
  • 6,304
  • 24
  • 83
  • 189
  • 1
    Per http://docs.guzzlephp.org/en/stable/quickstart.html#exceptions, you've disabled Guzzle's exceptions for 404 errors by doing `http_errors = false`, so it should get to your custom exception. – ceejayoz Oct 01 '19 at 13:26
  • @ceejayoz Ahhh sorry I meant to take that out, I actually want to record the errors not avoid them completely. Good spot though. – Rob Oct 01 '19 at 13:29
  • OK, in that case, Guzzle's gonna throw a `GuzzleHttp\Exception\ClientException` before you get to your `404 === $statuscode` stuff. You need to try/catch the Guzzle request call for a `GuzzleHttp\Exception\ClientException`. See the example in the docs I linked. (You may also want to catch `GuzzleHttp\Exception\ServerException` for 5xx errors.) – ceejayoz Oct 01 '19 at 13:32

0 Answers0