Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot retrieve error message using Symfony HttpClient

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
}
like image 648
Smaranda Dandy Avatar asked Oct 08 '19 14:10

Smaranda Dandy


1 Answers

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.

like image 83
LBA Avatar answered Nov 17 '22 06:11

LBA