feature #30559 [HttpClient] Parse common API error formats for better exception messages (dunglas)

This PR was squashed before being merged into the 4.3-dev branch (closes #30559).

Discussion
----------

[HttpClient] Parse common API error formats for better exception messages

| Q             | A
| ------------- | ---
| Branch?       | master <!-- see below -->
| Bug fix?      | no
| New feature?  | yes <!-- don't forget to update src/**/CHANGELOG.md files -->
| BC breaks?    | no     <!-- see https://symfony.com/bc -->
| Deprecations? | no <!-- don't forget to update UPGRADE-*.md and src/**/CHANGELOG.md files -->
| Tests pass?   | yes    <!-- please add some, will be required by reviewers -->
| Fixed tickets | n/a  <!-- #-prefixed issue number(s), if any -->
| License       | MIT
| Doc PR        | todo?

Use extra details provided by popular error formats following to improve HTTP exception messages.
The following formats are supported:

* Hydra (default in API Platform)
* RFC 7807 (followed by Symfony's [ConstraintViolationListNormalizer](https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Serializer/Normalizer/ConstraintViolationListNormalizer.php) and supported by API Platform and Apigility)
* JSON:API (because it respects the semantic of the RFC 7807)

It allows to write code like the following (here in a test context):

```php
    public function testBadRequest()
    {
        $this->expectException(ClientExceptionInterface::class);
        $this->expectExceptionCode(400); // HTTP status code
        $this->expectExceptionMessage(<<<ERROR
Validation Failed

users: This collection should contain 1 element or more.
users: The current logged in user must be part of the users owning this resource.
ERROR
);

        $response = (HttpClient::create())->request('POST', 'http://example.com/api/projects', [
            'json' => [
                'name' => 'My project',
            ],
        ]);
        $response->getContent();
    }
```

Port of https://github.com/api-platform/core/pull/2608#issuecomment-472510732.

Commits
-------

96df4464a1 [HttpClient] Parse common API error formats for better exception messages
This commit is contained in:
Fabien Potencier 2019-03-24 18:15:37 +01:00
commit 041f60f80a
2 changed files with 94 additions and 1 deletions

View File

@ -29,10 +29,41 @@ trait HttpExceptionTrait
$url = $response->getInfo('url');
$message = sprintf('HTTP %d returned for URL "%s".', $code, $url);
$httpCodeFound = false;
$isJson = false;
foreach (array_reverse($response->getInfo('raw_headers')) as $h) {
if (0 === strpos($h, 'HTTP/')) {
if ($httpCodeFound) {
break;
}
$message = sprintf('%s returned for URL "%s".', $h, $url);
break;
$httpCodeFound = true;
}
if (0 === stripos($h, 'content-type:')) {
if (preg_match('/\bjson\b/i', $h)) {
$isJson = true;
}
if ($httpCodeFound) {
break;
}
}
}
// Try to guess a better error message using common API error formats
// The MIME type isn't explicitly checked because some formats inherit from others
// Ex: JSON:API follows RFC 7807 semantics, Hydra can be used in any JSON-LD-compatible format
if ($isJson && $body = json_decode($response->getContent(false), true)) {
if (isset($body['hydra:title']) || isset($body['hydra:description'])) {
// see http://www.hydra-cg.com/spec/latest/core/#description-of-http-status-codes-and-errors
$separator = isset($body['hydra:title'], $body['hydra:description']) ? "\n\n" : '';
$message = ($body['hydra:title'] ?? '').$separator.($body['hydra:description'] ?? '');
} elseif (isset($body['title']) || isset($body['detail'])) {
// see RFC 7807 and https://jsonapi.org/format/#error-objects
$separator = isset($body['title'], $body['detail']) ? "\n\n" : '';
$message = ($body['title'] ?? '').$separator.($body['detail'] ?? '');
}
}

View File

@ -0,0 +1,62 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpClient\Tests\Exception;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpClient\Exception\HttpExceptionTrait;
use Symfony\Contracts\HttpClient\ResponseInterface;
/**
* @author Kévin Dunglas <dunglas@gmail.com>
*/
class HttpExceptionTraitTest extends TestCase
{
public function provideParseError()
{
yield ['application/ld+json', '{"hydra:title": "An error occurred", "hydra:description": "Some details"}'];
yield ['application/problem+json', '{"title": "An error occurred", "detail": "Some details"}'];
yield ['application/vnd.api+json', '{"title": "An error occurred", "detail": "Some details"}'];
}
/**
* @dataProvider provideParseError
*/
public function testParseError(string $mimeType, string $json): void
{
$response = $this->createMock(ResponseInterface::class);
$response
->method('getInfo')
->will($this->returnValueMap([
['http_code', 400],
['url', 'http://example.com'],
['raw_headers', [
'HTTP/1.1 400 Bad Request',
'Content-Type: '.$mimeType,
]],
]));
$response->method('getContent')->willReturn($json);
$e = new TestException($response);
$this->assertSame(400, $e->getCode());
$this->assertSame(<<<ERROR
An error occurred
Some details
ERROR
, $e->getMessage());
}
}
class TestException extends \Exception
{
use HttpExceptionTrait;
}