15

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
}

1 Answer 1

24

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.

Sign up to request clarification or add additional context in comments.

3 Comments

could you please clarify which meaningful wrapping functionality ypu mean here? Thank you
check what you can do with Response in the doc. If you just expect a string nothing special would be required, but checkout exception handling
It's designed this way so you don't need to check status code manually. You can still do so, but you have the option of using exception handling. It isn't a big difference for a single request, but it really comes in handy for complex code that does several requests in sequence.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.