5

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?

3
  • Is it possible that you want max_duration instead? Commented Apr 18, 2021 at 12:18
  • 1
    @Cerad It threw exception and can not be handled via try and catch aswell Commented Apr 18, 2021 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. Commented Apr 18, 2021 at 12:45

1 Answer 1

5

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

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.