3

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?

Sam
  • 1,424
  • 13
  • 28
  • Is it possible that you want [max_duration](https://symfony.com/doc/current/http_client.html#dealing-with-network-timeouts) instead? – Cerad Apr 18 '21 at 12:18
  • 1
    @Cerad It threw exception and can not be handled via try and catch aswell – Sam Apr 18 '21 at 12:35
  • Okay. This is perhaps why 'it does not work' is not always a useful description of a problem. So it is tossing an exception but your try/catch is not catching it. Maybe Laravel is intercepting it somehow? Just a guess. Good luck. – Cerad Apr 18 '21 at 12:45

1 Answers1

3

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();
    }

}
Sam
  • 1,424
  • 13
  • 28