Skip to content

Commit

Permalink
Allow returning a Promise in onRejected then() (#168)
Browse files Browse the repository at this point in the history
  • Loading branch information
ezimuel authored Feb 21, 2022
1 parent fc6a139 commit 16e8b6f
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,13 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.

## [Unreleased]

## [2.3.0] - 2022-02-x

### Changed

- Enabled the `$onRejected` callback of `HttpRejectedPromise` to return a promise for implementing a retry
mechanism [#168](https://github.com/php-http/httplug/pull/168)

## [2.2.0] - 2020-07-13

### Changed
Expand Down
16 changes: 16 additions & 0 deletions spec/Promise/HttpRejectedPromiseSpec.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Http\Client\Exception;
use Http\Client\Exception\TransferException;
use Http\Client\Promise\HttpFulfilledPromise;
use Http\Promise\Promise;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
Expand Down Expand Up @@ -87,4 +88,19 @@ function it_throws_not_http_exception()
throw new \Exception();
});
}

function it_returns_a_promise_when_rejected(ResponseInterface $response)
{
$exception = new TransferException();
$this->beConstructedWith($exception);

$promise = $this->then(null, function (Exception $exceptionReceived) use($exception, $response) {
return new HttpFulfilledPromise($response->getWrappedObject());
});

$promise->shouldHaveType('Http\Promise\Promise');
$promise->shouldHaveType('Http\Client\Promise\HttpFulfilledPromise');
$promise->getState()->shouldReturn(Promise::FULFILLED);
$promise->wait()->shouldReturnAnInstanceOf('Psr\Http\Message\ResponseInterface');
}
}
7 changes: 6 additions & 1 deletion src/Promise/HttpRejectedPromise.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,12 @@ public function then(callable $onFulfilled = null, callable $onRejected = null)
}

try {
return new HttpFulfilledPromise($onRejected($this->exception));
$result = $onRejected($this->exception);
if ($result instanceof Promise) {
return $result;
}

return new HttpFulfilledPromise($result);
} catch (Exception $e) {
return new self($e);
}
Expand Down

0 comments on commit 16e8b6f

Please sign in to comment.