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

This commit is contained in:
Kévin Dunglas 2019-03-13 23:02:02 +01:00 committed by Fabien Potencier
parent 59e63805a3
commit 96df4464a1
2 changed files with 94 additions and 1 deletions

View File

@ -26,10 +26,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;
}