swisnl / json-api-client

A PHP package for mapping remote {json:api} resources to Eloquent like models and collections.
MIT License
205 stars 24 forks source link

401 responses don't result in an exception #95

Closed tomasvanrijsse closed 2 years ago

tomasvanrijsse commented 2 years ago

We had an integration that failed because of an expired api key. The error we had however wasn't useful at all because the json-api-client simply returned an empty collection. So our script failed when it tried to use that data.

We would have expected that HTTP errors like 401, 404 and others would result in a PHP Exception. The reason that this doesn't happen is because of this line:

https://github.com/swisnl/json-api-client/blob/b8fff65053af28fbc89214d485b3713f011fcf78/src/Client.php#L160

The Guzzle Client sendRequest() method has hardcoded $options[RequestOptions::HTTP_ERRORS] = false;

https://github.com/guzzle/guzzle/blob/e3ff079b22820c2029d4c2a87796b6a0b8716ad8/src/Client.php#L131-L138

Possible implementation

I would suggest to change Client.php line 160 like this

-return $this->client->sendRequest($this->buildRequest($method, $endpoint, $body, $headers));
+return $this->client->send($this->buildRequest($method, $endpoint, $body, $headers));
JaZo commented 2 years ago

Hi @tomasvanrijsse, what you describe is expected behaviour. This client requires a PSR-18 HTTP Client and these do not throw an exception on 4xx or 5xx errors. You can find more information about handling errors in the documentation. If you want your client to always throw errors, maybe you can create a wrapper client that does so.