为什么在Symfony HTTP Client 遇到错误时无法访问响应内容,而是抛出异常?

Why can't I access the response content when the Symfony HTTP Client encounters an error, and an exception is thrown instead?

我想使用 Symfony HttpClient 请求从 OAUTH 服务器检索用户信息,但是当遇到错误响应时我无法直接获取响应,因为客户端抛出异常。

我的用户提供者:

    public function loadUserByUsername($username)
    {
        try {
            $response = $this->httpClient->request(
                'GET',
                $this->baseUrl . '/userinfo',
                [
                    'headers' => [
                        'Accept' => 'application/json',
                        'Content-Type' => 'application/json'
                    ],
                    'auth_bearer' => $username
                ]
            );

            var_dump($response->toArray());die;

        } catch (\Exception $e) {
            var_dump($e->getMessage());die;
            throw new UsernameNotFoundException($e->getMessage());
        }
    }

当我调用 $response->toArray()$response->getContent() 时,抛出异常并且我在 Postman

上收到以下错误消息
<pre class='xdebug-var-dump' dir='ltr'>
<small>/var/www/html/backend/src/Security/Provider/KeycloakUserProvider.php:50:</small><small>string</small> <font color='#cc0000'>'HTTP/2 401  returned for &quot;https://oauth_server/userinfo&quot;.'</font> <i>(length=127)</i>
</pre>

浏览器收到的响应示例:

{"error":"invalid_request","error_description":"Token not provided"}

为什么我不能通过调用 $response->toArray() 直接访问响应?

只要响应的状态代码不是“好”(例如在 300-599 范围内),响应就会被视为 异常,您应该处理它.

这已明确记录here:

When the HTTP status code of the response is in the 300-599 range (i.e. 3xx, 4xx or 5xx), the getHeaders(), getContent() and toArray() methods throw an appropriate exception, all of which implement the HttpExceptionInterface.

To opt-out from this exception and deal with 300-599 status codes on your own, pass false as the optional argument to every call of those methods, e.g. $response->getHeaders(false);.

如果不希望客户端在遇到非OK响应时抛出异常,需要将false传给getContent()toArray().

例如

$rawResponse   = $response->getContents(false);
$arrayResponse = $response->toArray(false);

在您的代码中显式处理异常并没有错,并且会使您的应用程序更好地表达它遇到的情况。 “不良”应被视为异常,并进行相应处理。