[HttpClient] Check status code before decoding content in TraceableResponse

This commit is contained in:
Robin Chalas 2020-11-03 17:55:17 +01:00
parent a29af81af4
commit e5595dae73
2 changed files with 25 additions and 12 deletions

View File

@ -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

View File

@ -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();
}
}