Skip to content

Commit 16e8b6f

Browse files
authored
Allow returning a Promise in onRejected then() (#168)
1 parent fc6a139 commit 16e8b6f

File tree

3 files changed

+29
-1
lines changed

3 files changed

+29
-1
lines changed

CHANGELOG.md

+7
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,13 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
99

1010
## [Unreleased]
1111

12+
## [2.3.0] - 2022-02-x
13+
14+
### Changed
15+
16+
- Enabled the `$onRejected` callback of `HttpRejectedPromise` to return a promise for implementing a retry
17+
mechanism [#168](https://github.com/php-http/httplug/pull/168)
18+
1219
## [2.2.0] - 2020-07-13
1320

1421
### Changed

spec/Promise/HttpRejectedPromiseSpec.php

+16
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use Http\Client\Exception;
66
use Http\Client\Exception\TransferException;
7+
use Http\Client\Promise\HttpFulfilledPromise;
78
use Http\Promise\Promise;
89
use PhpSpec\ObjectBehavior;
910
use Prophecy\Argument;
@@ -87,4 +88,19 @@ function it_throws_not_http_exception()
8788
throw new \Exception();
8889
});
8990
}
91+
92+
function it_returns_a_promise_when_rejected(ResponseInterface $response)
93+
{
94+
$exception = new TransferException();
95+
$this->beConstructedWith($exception);
96+
97+
$promise = $this->then(null, function (Exception $exceptionReceived) use($exception, $response) {
98+
return new HttpFulfilledPromise($response->getWrappedObject());
99+
});
100+
101+
$promise->shouldHaveType('Http\Promise\Promise');
102+
$promise->shouldHaveType('Http\Client\Promise\HttpFulfilledPromise');
103+
$promise->getState()->shouldReturn(Promise::FULFILLED);
104+
$promise->wait()->shouldReturnAnInstanceOf('Psr\Http\Message\ResponseInterface');
105+
}
90106
}

src/Promise/HttpRejectedPromise.php

+6-1
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,12 @@ public function then(callable $onFulfilled = null, callable $onRejected = null)
2727
}
2828

2929
try {
30-
return new HttpFulfilledPromise($onRejected($this->exception));
30+
$result = $onRejected($this->exception);
31+
if ($result instanceof Promise) {
32+
return $result;
33+
}
34+
35+
return new HttpFulfilledPromise($result);
3136
} catch (Exception $e) {
3237
return new self($e);
3338
}

0 commit comments

Comments
 (0)