diff --git a/src/Symfony/Component/HttpClient/Response/TraceableResponse.php b/src/Symfony/Component/HttpClient/Response/TraceableResponse.php index 2fe78f4574..b574310253 100644 --- a/src/Symfony/Component/HttpClient/Response/TraceableResponse.php +++ b/src/Symfony/Component/HttpClient/Response/TraceableResponse.php @@ -52,24 +52,24 @@ class TraceableResponse implements ResponseInterface public function getContent(bool $throw = true): string { - $this->content = $this->response->getContent(false); - - if ($throw) { - $this->checkStatusCode($this->response->getStatusCode()); + try { + return $this->content = $this->response->getContent(false); + } finally { + if ($throw) { + $this->checkStatusCode($this->response->getStatusCode()); + } } - - return $this->content; } public function toArray(bool $throw = true): array { - $this->content = $this->response->toArray(false); - - if ($throw) { - $this->checkStatusCode($this->response->getStatusCode()); + try { + return $this->content = $this->response->toArray(false); + } finally { + if ($throw) { + $this->checkStatusCode($this->response->getStatusCode()); + } } - - return $this->content; } public function cancel(): void diff --git a/src/Symfony/Component/HttpClient/Tests/TraceableHttpClientTest.php b/src/Symfony/Component/HttpClient/Tests/TraceableHttpClientTest.php index 9b6752f7b6..43012e99c2 100755 --- a/src/Symfony/Component/HttpClient/Tests/TraceableHttpClientTest.php +++ b/src/Symfony/Component/HttpClient/Tests/TraceableHttpClientTest.php @@ -16,6 +16,7 @@ use Symfony\Component\HttpClient\MockHttpClient; use Symfony\Component\HttpClient\NativeHttpClient; use Symfony\Component\HttpClient\Response\MockResponse; use Symfony\Component\HttpClient\TraceableHttpClient; +use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface; use Symfony\Contracts\HttpClient\HttpClientInterface; use Symfony\Contracts\HttpClient\Test\TestHttpServer; @@ -100,4 +101,16 @@ class TraceableHttpClientTest extends TestCase $this->assertGreaterThan(1, \count($chunks)); $this->assertSame('Symfony is awesome!', implode('', $chunks)); } + + public function testToArrayChecksStatusCodeBeforeDecoding() + { + $this->expectException(ClientExceptionInterface::class); + + $sut = new TraceableHttpClient(new MockHttpClient($responseFactory = function (): MockResponse { + return new MockResponse('Errored.', ['http_code' => 400]); + })); + + $response = $sut->request('GET', 'https://example.com/foo/bar'); + $response->toArray(); + } }