Why Guzzle onrejected function in promise-then still throw an exception?

22 Views Asked by At

I found that the $promise->wait() function will throw an exception and I must use try-catch to handle exception again.

$promise = $this->client->sendAsync($request);
$promise->then(
    function ($response) use (...){
        //do something
    },
    function ($exception) {
        $this->logger->error("Failed " . $exception->getMessage());
    }
);
try{
    $promise->wait(true);
}catch(Exception $exception){
    $this->logger->error("Failed " . $exception->getMessage());
}

The error info will be recorded by logger twice. Is there any method that the exception can be handled in onrejected fuction? Or any better way to handle such exception?

Here's my error: PHP Fatal error: Uncaught GuzzleHttp\Exception\ClientException: Client error:...

Thank you very much for your help.

I have tried this

$promise->then(
//...
)->then(
//...
);

but not work.

1

There are 1 best solutions below

0
user23674741 On

Well, maybe I figure it out. The exception is thrown by wait(), because there is a default param 'unwrap'.

replace

try{
    $promise->wait(true);
}catch(Exception $exception){
    $this->logger->error("Failed " . $exception->getMessage());
}

with

Promise\Utils::settle($promise)->wait();

or

$promise->wait(false);