簡體   English   中英

如何從錯誤處理程序中調度操作並立即在redux-observable中打破其余的Observable鏈?

[英]How to dispatch actions from an error handler and immediately break the rest of the Observable chain in redux-observable?

為了處理401個未經授權的請求,我試圖用errorHandler包裝所有的api請求:

const apiGet (props) = ajax({
  headers,
  method: 'GET',
  ...props
}).catch(res => {
  if (res.status === 401)
    return Observable.of(unauthorizedAction();
  else
    return Observable.throw(res);
});

理想情況下,我可以通過以下方式使用它,知道401會觸發unauthorizedAction() ,而500則會由handleOtherErrors處理。

action.ofType(SOME_ACTION) => 
  apiGet(something)
    .map(res => doSomethingWithResponse(res))
    .catch(handleOtherErrors);

但是,通過上面的設置,當我收到401響應時會出現問題。 errorHandler按預期返回unauthorizedAction,但隨后它繼續映射操作並嘗試對響應執行某些操作,而不是調度該操作並終止Observable鏈。

所以,我的問題是,我怎么能在我的錯誤處理程序中做這樣的事情?

.catch(res => {
  if (res.status === 401)
    // Dispatch an action, but stop the rest of the chain
  else
    return Observable.throw(res);
}).map(...restOfChain)
  .catch(additionalErrorHandlerForNon401);

運算符是一系列Observable,它們不知道之前或之后的運算符是如何做什么的。 可以創建自己的自定義系列操作符,這些操作符具有這樣的知識和能力,但我不推薦它,因為它違背了傳統的RxJS模式。

相反,您可以傳遞將使用map為它們應用的結果選擇器。

// provides a default `resultSelector` that is basically a noop
const apiGet = (props, resultSelector = res => res) =>
  ajax({ headers, method: 'GET', ...props })
    .map(res => resultSelector(res))
    .catch(res => {
      if (res.status === 401)
        return Observable.of(unauthorizedAction());
      else
        return Observable.throw(res);
    });

它可以像這樣使用:

apiGet(something, res => doSomethingWithResponse(res))
  .catch(handleOtherErrors)

當動作創建者與resultSelector具有相同的簽名時,您甚至可以按原樣傳遞它

apiGet(something, doSomethingWithResponse)
  .catch(handleOtherErrors)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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