gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:39:09 33 4
gpt4 key购买 nike

我想使用 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);

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

关于php - 为什么在Symfony HTTP Client 遇到错误时无法访问响应内容,而是抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68303486/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com