diff --git a/src/Illuminate/Http/Client/Response.php b/src/Illuminate/Http/Client/Response.php index 2b34293a046f..64331cfc39e9 100644 --- a/src/Illuminate/Http/Client/Response.php +++ b/src/Illuminate/Http/Client/Response.php @@ -343,6 +343,19 @@ public function throwIf($condition) return value($condition, $this) ? $this->throw(func_get_args()[1] ?? null) : $this; } + /** + * Throw an exception if a server or client error occurred and the given condition evaluates to false. + * + * @param \Closure|bool $condition + * @return $this + * + * @throws \Illuminate\Http\Client\RequestException + */ + public function throwUnless($condition) + { + return $this->throwIf(! $condition); + } + /** * Throw an exception if the response status code matches the given code. * diff --git a/tests/Http/HttpClientTest.php b/tests/Http/HttpClientTest.php index e2d1641ad31c..febc488c3a91 100644 --- a/tests/Http/HttpClientTest.php +++ b/tests/Http/HttpClientTest.php @@ -3188,6 +3188,35 @@ public function testRequestExceptionIsNotThrownIfConditionIsNotSatisfied() $this->assertSame('{"result":{"foo":"bar"}}', $response->body()); } + public function testRequestExceptionIsThrownWhenUnlessConditionIsNotSatisfied() + { + $this->factory->fake([ + '*' => $this->factory::response('', 400), + ]); + + $exception = null; + + try { + $this->factory->get('http://foo.com/api')->throwUnless(false); + } catch (RequestException $e) { + $exception = $e; + } + + $this->assertNotNull($exception); + $this->assertInstanceOf(RequestException::class, $exception); + } + + public function testRequestExceptionIsNotThrownWhenUnlessConditionIsSatisfied() + { + $this->factory->fake([ + '*' => $this->factory::response(['result' => ['foo' => 'bar']], 400), + ]); + + $response = $this->factory->get('http://foo.com/api')->throwUnless(true); + + $this->assertSame('{"result":{"foo":"bar"}}', $response->body()); + } + public function testRequestExceptionIsThrowIfConditionClosureIsSatisfied() { $this->factory->fake([