Skip to content

Commit

Permalink
Handle undecodable responses gracefully
Browse files Browse the repository at this point in the history
Introduced a try-catch block in the data() method to catch
`NotDecodableException` when attempting to decode response data. In such
cases, decoding will now default to an empty array instead of throwing
an unhandled exception. Moreover, clarified method return types in doc
comments for `onError`, `throw`, and `throwIf` to reflect the generic
`Response<T>` type.
  • Loading branch information
jenky committed Jan 5, 2024
1 parent fe40221 commit b5a25de
Showing 1 changed file with 13 additions and 3 deletions.
16 changes: 13 additions & 3 deletions src/Response.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Fansipan\Contracts\DecoderInterface;
use Fansipan\Contracts\MapperInterface;
use Fansipan\Exception\HttpException;
use Fansipan\Exception\NotDecodableException;
use LogicException;
use Psr\Http\Message\ResponseInterface;

Expand Down Expand Up @@ -57,7 +58,11 @@ public function body(): string
public function data(): array
{
if (! $this->decoded) {
$this->decoded = Util::iteratorToArray($this->decode());
try {
$this->decoded = Util::iteratorToArray($this->decode());
} catch (NotDecodableException $e) {
$this->decoded = [];
}
}

return $this->decoded;
Expand All @@ -80,12 +85,12 @@ public function object(): ?object
/**
* Get the decoded body the response.
*
* @throws \Fansipan\Exception\NotDecodableException
* @throws NotDecodableException
*/
public function decode(): iterable
{
if (! $this->decoder instanceof DecoderInterface) {
return [];
throw NotDecodableException::create();
}

return $this->decoder->decode($this->response);
Expand Down Expand Up @@ -191,6 +196,8 @@ public function serverError(): bool

/**
* Execute the given callback if there was a server or client error.
*
* @return Response<T>
*/
public function onError(callable $callback): self
{
Expand Down Expand Up @@ -228,6 +235,8 @@ public function toException(): ?HttpException
/**
* Throw an exception if a server or client error occurred.
*
* @return Response<T>
*
* @throws \Fansipan\Exception\HttpException
*/
public function throw(): self
Expand Down Expand Up @@ -255,6 +264,7 @@ public function throw(): self
* Throw an exception if a server or client error occurred and the given condition evaluates to true.
*
* @param \Closure|bool $condition
* @return Response<T>
*
* @throws \Fansipan\Exception\HttpException
*/
Expand Down

0 comments on commit b5a25de

Please sign in to comment.