簡體   English   中英

食屍鬼6-承諾-捕捉例外

[英]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。 如果onFulfilledonRejected拋出異常epromise2必須以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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM