Reputation: 222
I use Symfony HttpClient to call an external API. When the status code is 200 I can use getContent()
method to retrieve the API response. If the API response is 400, a 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
}
Upvotes: 14
Views: 8597
Reputation: 4089
You can use
$response->getContent(false)
to get the response and not an error thrown.
Explanation from Code:
public function getContent(bool $throw = true): string
Note that you lose a bit of the very meaningful wrapping functionality HttpClient provides you here.
Upvotes: 22