Guzzle 6 - Promises - Crash Exception

I do not understand how to catch the exception (forward it) inside the onReject handler. I was wondering if anyone could point me in the right direction on how to do this.

I send several asynchronous requests, and when someone fails, "Fuzzy exception was encountered - Type: GuzzleHttp \ Exception \ ClientException", it never gets.

I read:

But it is not clear why the following does not work. I understand that when a ClientException is thrown inside the onReject (RequestException), it will then push it further to the next onReject (ClientException) and be correctly caught.

Any help would be appreciated.

$client = new GuzzleHttp\Client(); $promise = $client->requestAsync('POST', SOME_URL, [ ... SOME_PARAMS ... ]); $promise->then( function (ResponseInterface $res) { //ok }, function (RequestException $e) { //inside here throws a ClientException } )->then(null, function (ClientException $e) { //Why does it not get caught/forwarded to this error handler? }); 
+6
source share
2 answers

According to the buzz documentation,

If an exception is thrown in the $ onRejected callback, subsequent $ onRejected callbacks are called with the exception thrown as the reason.

So this should work:

 $promise ->then( function (ResponseInterface $res) { // this will be called when the promise resolves return $someVal; }, function (RequestException $e) { // this will be called when the promise resolving failed // if you want this to bubble down further the then-line, just re-throw: throw $e; } ) ->then( function ($someVal) { }, function (RequestException $e) { // now the above thrown Exception should be passed in here }); 
+1
source

Guzzle Promises follow Promises / A + . Therefore, we can rely on the official description to understand the behavior that interests you:

2.2.7.1. If either onFulfilled or onRejected returns x , run the promise resolution procedure [[Resolve]](promise2, x) .

2.2.7.2. If either onFulfilled or onRejected throws an exception e , promise2 must be rejected with e as the reason.

And later for case 2.2.7.2 :

2.3.2. If x is a promise, accept its state

Therefore, you can either execute the solution suggested by @lkoell or return RejectedPromise from the callback, which will cause the subsequent promise to accept the rejected state.

 $promiseA = $promise ->then( function (ResponseInterface $res) { //ok }, function (RequestException $e) { //This will force $promiseB adopt $promiseC state and get rejected return $promiseC = new RejectedPromise($clientException); } ); $promiseB = $promiseA->then(null, function (ClientException $e) { // There you will get rejection }); 

This method is more flexible since you can reject a promise not only with an exception, but also for any reason (other than a promise).

0
source

All Articles