bug #38977 [HttpClient] Check status code before decoding content in TraceableResponse (chalasr)

This PR was merged into the 5.1 branch.

Discussion
----------

[HttpClient] Check status code before decoding content in TraceableResponse

| Q             | A
| ------------- | ---
| Branch?       | 5.1
| Bug fix?      | yes
| New feature?  | no
| Deprecations? | np
| Tickets       | -
| License       | MIT
| Doc PR        | -

Using `toArray()` on the response of a traceable client, the status code is currently checked after json decoding, which leads to `JsonException` being thrown instead of `ClientException`.
It should be the opposite, as for non-traceable responses.

Commits
-------

e5595dae73 [HttpClient] Check status code before decoding content in TraceableResponse
This commit is contained in:
Nicolas Grekas 2020-11-03 21:22:18 +01:00
commit ff7ffdf22a
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();
}
}