@@ -1214,6 +1214,8 @@ response and get remaining contents that might come back in a new timeout, etc.
1214
1214
1215
1215
Use the ``max_duration `` option to limit the time a full request/response can last.
1216
1216
1217
+ .. _http-client_network-errors :
1218
+
1217
1219
Dealing with Network Errors
1218
1220
~~~~~~~~~~~~~~~~~~~~~~~~~~~
1219
1221
@@ -1975,6 +1977,59 @@ test it in a real application::
1975
1977
}
1976
1978
}
1977
1979
1980
+ Simulate a Transport Exception
1981
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1982
+
1983
+ When making HTTP requests, it sometimes occurs an error at transport level.
1984
+ You can find more information about transport errors it in the
1985
+ :ref: `Network Errors <http-client_network-errors >` section.
1986
+
1987
+ It may be useful to test how your application behaves in case of a transport
1988
+ error. :class: `Symfony\\ Component\\ HttpClient\\ Response\\ MockResponse ` allows
1989
+ you to do so, by yielding the exception from its body::
1990
+
1991
+ // ExternalArticleServiceTest.php
1992
+ use PHPUnit\Framework\TestCase;
1993
+ use Symfony\Component\HttpClient\MockHttpClient;
1994
+ use Symfony\Component\HttpClient\Response\MockResponse;
1995
+
1996
+ final class ExternalArticleServiceTest extends TestCase
1997
+ {
1998
+ // ...
1999
+
2000
+ public function testTransportLevelError(): void
2001
+ {
2002
+ $requestData = ['title' => 'Testing with Symfony HTTP Client'];
2003
+ $httpClient = new MockHttpClient([
2004
+ // You can create the exception directly in the body...
2005
+ new MockResponse([new \RuntimeException('Error at transport level')]),
2006
+
2007
+ // ... or you can yield the exception from a callback
2008
+ new MockResponse((static function (): \Generator {
2009
+ yield new TransportException('Error at transport level');
2010
+ })()),
2011
+ ]);
2012
+
2013
+ $service = new ExternalArticleService($httpClient);
2014
+
2015
+ try {
2016
+ $service->createArticle($requestData);
2017
+
2018
+ // An exception should have been thrown in `createArticle()`, so this line should never be reached
2019
+ $this->fail();
2020
+ } catch (TransportException $e) {
2021
+ $this->assertEquals(new \RuntimeException('Error at transport level'), $e->getPrevious());
2022
+ $this->assertSame('Error at transport level', $e->getMessage());
2023
+ }
2024
+ }
2025
+ }
2026
+
2027
+ .. versionadded :: 6.1
2028
+
2029
+ Being allowed to pass an exception directly to the body of a
2030
+ :class: `Symfony\\ Component\\ HttpClient\\ Response\\ MockResponse ` was
2031
+ introduced in Symfony 6.1.
2032
+
1978
2033
.. _`cURL PHP extension` : https://www.php.net/curl
1979
2034
.. _`Zlib PHP extension` : https://www.php.net/zlib
1980
2035
.. _`PSR-17` : https://www.php-fig.org/psr/psr-17/
0 commit comments