@@ -1211,6 +1211,8 @@ response and get remaining contents that might come back in a new timeout, etc.
12111211
12121212 Use the ``max_duration `` option to limit the time a full request/response can last.
12131213
1214+ .. _http-client_network-errors :
1215+
12141216Dealing with Network Errors
12151217~~~~~~~~~~~~~~~~~~~~~~~~~~~
12161218
@@ -1931,6 +1933,59 @@ test it in a real application::
19311933 }
19321934 }
19331935
1936+ Simulate a Transport Exception
1937+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1938+
1939+ When making HTTP requests, it sometimes occurs an error at transport level.
1940+ You can find more information about transport errors it in the
1941+ :ref: `Network Errors <http-client_network-errors >` section.
1942+
1943+ It may be useful to test how your application behaves in case of a transport
1944+ error. :class: `Symfony\\ Component\\ HttpClient\\ Response\\ MockResponse ` allows
1945+ you to do so, by yielding the exception from its body::
1946+
1947+ // ExternalArticleServiceTest.php
1948+ use PHPUnit\Framework\TestCase;
1949+ use Symfony\Component\HttpClient\MockHttpClient;
1950+ use Symfony\Component\HttpClient\Response\MockResponse;
1951+
1952+ final class ExternalArticleServiceTest extends TestCase
1953+ {
1954+ // ...
1955+
1956+ public function testTransportLevelError(): void
1957+ {
1958+ $requestData = ['title' => 'Testing with Symfony HTTP Client'];
1959+ $httpClient = new MockHttpClient([
1960+ // You can create the exception directly in the body...
1961+ new MockResponse([new \RuntimeException('Error at transport level')]),
1962+
1963+ // ... or you can yield the exception from a callback
1964+ new MockResponse((static function (): \Generator {
1965+ yield new TransportException('Error at transport level');
1966+ })()),
1967+ ]);
1968+
1969+ $service = new ExternalArticleService($httpClient);
1970+
1971+ try {
1972+ $service->createArticle($requestData);
1973+
1974+ // An exception should have been thrown in `createArticle()`, so this line should never be reached
1975+ $this->fail();
1976+ } catch (TransportException $e) {
1977+ $this->assertEquals(new \RuntimeException('Error at transport level'), $e->getPrevious());
1978+ $this->assertSame('Error at transport level', $e->getMessage());
1979+ }
1980+ }
1981+ }
1982+
1983+ .. versionadded :: 6.1
1984+
1985+ Being allowed to pass an exception directly to the body of a
1986+ :class: `Symfony\\ Component\\ HttpClient\\ Response\\ MockResponse ` was
1987+ introduced in Symfony 6.1.
1988+
19341989.. _`cURL PHP extension` : https://www.php.net/curl
19351990.. _`Zlib PHP extension` : https://www.php.net/zlib
19361991.. _`PSR-17` : https://www.php-fig.org/psr/psr-17/
0 commit comments