无法使用 Symfony HttpClient 检索错误消息 [英] Cannot retrieve error message using Symfony HttpClient
本文介绍了无法使用 Symfony HttpClient 检索错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用 Symfony HttpClient 来调用外部 api.当 statusCode 为 200 时,我可以使用 getContent()
方法来检索 API 响应.如果 API 响应为 400,则抛出 ClientException 并且我无法获取外部 API 消息.
I use Symfony HttpClient to call an external api. When the stastusCode is 200 I can use getContent()
method to retrieve the API response. If the API response is 400 ClientException is thrown and I cannot get the external API message.
$httpClient = HttpClient::create();
$response = $httpClient->request($method, $url);
if (200 !== $response->getStatusCode()) {
$apiResponse['statusCode'] = $response->getStatusCode();
$httpInfo = $response->getInfo();
$content = $response->getContent(); //this throws ClientException
}
推荐答案
可以使用
$response->getContent(false)
得到响应而不是抛出错误.
to get the response and not an error thrown.
代码说明:
public function getContent(bool $throw = true): string
请注意,您在这里失去了 HttpClient 为您提供的一些非常有意义的包装功能.
Note that you lose a bit of the very meaningful wrapping functionality HttpClient provides you here.
这篇关于无法使用 Symfony HttpClient 检索错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文