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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With