Reputation: 1559
I am using Symfony HTTP client in an event subscriber and I set timeout to 0.1. The problem is I want the code to skip the HTTP request if took more than 0.1 second and it timedout and meanwhile no error/exception needs to be thrown. I tried try and catch but it does not work.
public function checkToken()
{
try {
$response = $this->client->request('POST','url/of/api', [
'json' => ['token' => $_ENV['USER_TOKEN']],
'timeout' => 0.1,
]);
}catch (\Exception $e){
}
}
Why it can not be handled via try and catch?
Upvotes: 5
Views: 9159
Reputation: 1559
Its because responses are lazy in Symfony. As this document mentioned: https://symfony.com/doc/current/http_client.html#handling-exceptions
A solution is to call getContent method in try section.
private $client;
private $user_data;
public function __construct(HttpClientInterface $client)
{
$this->client = $client;
}
public function checkToken(RequestEvent $event)
{
try {
$response = $this->client->request('POST', 'url/of/api', [
'json' => ['token' => $_ENV['USER_TOKEN']],
'timeout' => 0.1,
]);
$this->user_data = $response->getContent();
} catch (\Exception $e) {
echo $e->getMessage();
}
}
Upvotes: 5