Thanks to visit codestin.com
Credit goes to github.com

Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 24, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,41 @@ public function __construct(ResponseInterface $response)
$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'] ?? '');
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* 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 <[email protected]>
*/
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;
}