[英]Guzzle 6 - Promises - Catching Exceptions
我不太了解如何在onReject处理程序中捕获异常(将其转发)。 我想知道是否有人可以向我指出如何成功做到这一点的正确方向。
我正在发送一些异步请求,当一个请求失败并显示“遇到未捕获的异常-类型:GuzzleHttp \\ Exception \\ ClientException”时,它永远不会被捕获。
我读过了:
但尚不清楚以下原因为何不起作用。 我的理解是,将ClientException扔到onReject(RequestException)内时,它将把它进一步推到下一个onReject(ClientException)并被正确捕获。
任何帮助,将不胜感激。
$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?
});
根据枪口文件,
如果在$ onRejected回调中引发了异常,则随后的$ onRejected回调将以引发的异常为原因进行调用。
所以这应该工作:
$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
});
食欲承诺 遵循 Promises / A +标准。 因此,我们可以依靠官方描述来掌握您好奇的行为:
2.2.7.1。 如果onFulfilled或onRejected返回值
x
,请运行Promise Resolution Procedure[[Resolve]](promise2, x)
。2.2.7.2。 如果
onFulfilled
或onRejected
抛出异常e
,promise2
必须以e
为理由拒绝promise2
。
后来对于2.2.7.2情况:
2.3.2。 如果
x
是一个承诺,则采用其状态
因此,您可以遵循@lkoell提出的解决方案,也可以从回调中返回RejectedPromise
,这将迫使后续的诺言采用被rejected
状态。
$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
});
这种方式更加灵活,因为您不仅可以拒绝例外的承诺,而且可以拒绝任何原因(承诺之外的其他原因)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.