Skip to content

[HttpClient] Update http_client.rst #14499

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 5 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 12 additions & 14 deletions http_client.rst
Original file line number Diff line number Diff line change
Expand Up @@ -891,20 +891,18 @@ Handling Exceptions
~~~~~~~~~~~~~~~~~~~

When the HTTP status code of the response is in the 300-599 range (i.e. 3xx,
4xx or 5xx) your code is expected to handle it. If you don't do that, the
``getHeaders()``, ``getContent()`` and ``toArray()`` methods throw an appropriate exception, all of
which implement the :class:`Symfony\\Contracts\\HttpClient\\Exception\\HttpExceptionInterface`::

// the response of this request will be a 403 HTTP error
$response = $client->request('GET', 'https://httpbin.org/status/403');

// this code results in a Symfony\Component\HttpClient\Exception\ClientException
// because it doesn't check the status code of the response
$content = $response->getContent();

// pass FALSE as the optional argument to not throw an exception and return
// instead the original response content (even if it's an error message)
$content = $response->getContent(false);
4xx or 5xx), the ``getHeaders()``, ``getContent()`` and ``toArray()`` methods
throw an appropriate exception, all of which implement the
:class:`Symfony\\Contracts\\HttpClient\\Exception\\HttpExceptionInterface`.

To opt-out from this exception and deal with 300-599 status codes on your own,
pass ``false`` as the optional argument to every call of those methods,
e.g. ``$response->getHeaders(false);``.

If you do not call any of these 3 methods at all, the exception will still be thrown
when the ``$response`` object is destructed (i.e. when the Symfony kernel delivers the final response).
Calling ``$response->getStatusCode()`` is enough to disable this behavior
(but then don't miss checking the status code yourself).

While responses are lazy, their destructor will always wait for headers to come
back. This means that the following request *will* complete; and if e.g. a 404
Expand Down