php - Guzzle 6 - Promises - 捕获异常

标签 php guzzle guzzle6

我真的不明白如何在 onReject 处理程序中捕获异常(转发它)。我想知道是否有人可以指出正确的方向,告诉我如何成功地做到这一点。

我正在发送一些异步请求,当一个请求失败并显示“遇到未捕获的异常 - 类型:GuzzleHttp\Exception\ClientException”时,它永远不会被捕获。

我已阅读:

但不清楚为什么以下内容不起作用。我的理解是,当在 onReject (RequestException) 中抛出 ClientException 时,它将进一步向下推到下一个 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?
});

最佳答案

根据 guzzle 文档,

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

所以这应该可行:

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

关于php - Guzzle 6 - Promises - 捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37646590/

相关文章:

php - $变量 = $_POST ['variable'].$_GET ['variable'];这是可以接受的吗?

php - 如何将以逗号分隔的多个值输入到表中?

PHP imap_append - 设置 SEEN 选项

用于 HTTP keep-alive 的 PHP Guzzle 客户端

php - Symfony 2 - Guzzle 6.X HTTP |获得 body react

php - 使用 Guzzle 6 将文件上传到 API 端点

php - 将字符串编码为字符代码

php - Guzzle 不发送自定义标题

post - 如何使用查询字符串参数制作 Guzzle 帖子

php - 使用 Guzzle 6 获取 API 调用持续时间的最佳方法是什么