跨包装"catchError"处理程序的函数调用组合可观察量



我正在为我的所有史诗实现一个全局错误处理程序,它应该处理会话错误。我的问题是如何在我包装的"catchError"函数中组合 redux 操作的可观察量。

我想保留原始 catchError 运算符的行为,该运算符期望可观察量作为返回值。

我已经有一个解决方案,它需要一系列简单的操作。但这不是我真正想要的。

catchError.ts

import { catchError } from 'rxjs/operators';
import { sessionIsUnauthorizedAction } from '../action/SessionAction';
export default (errorHandler) => catchError(error => {
return of(
error.response.status === 401 && sessionIsUnauthorizedAction(),
errorHandler(error)
);
})

我的史诗

import catchError from 'my/wrapped/catchError';
export const myEpic: Epic<RootAction, RootAction> = action$ =>
action$.pipe(
filter(isActionOf(myAction)),
switchMap(
({ payload: { DTO } }) => {
return from(backendCall(DTO)).pipe(
switchMap(
() => of(
myActionSucceeded(),
anotherAction({ id: 'other-payload' })
)
)
);
}
),
catchError(error => of(
myActionFailed(),
anotherAction({ id: 'other-payload' })
))
);

当我在史诗中包装的 catchError 运算符被触发(由错误(时,它不仅应该调用 sessionIsUnauthorizedAction,还应该调用 myActionFailed 和 otherAction。

实际上,只有会话是未经授权的操作被调用并抛出错误:

Error: Actions must be plain objects. Use custom middleware for async actions

您的错误处理程序传入

catchError(error => of(
myActionFailed(),
anotherAction({ id: 'other-payload' })
))

返回一个可观察量,因此您可以获得一个操作和其他可观察量

export default (errorHandler) => catchError(error => {
return of(
error.response.status === 401 && sessionIsUnauthorizedAction(),
of(myActionFailed(), anotherAction({ id: 'other-payload' }))
);
})

你可以连接它们

import { concat } from 'rxjs';
export default (errorHandler) => catchError(error => {
return concat(
of(error.response.status === 401 && sessionIsUnauthorizedAction()),
errorHandler(error)
)
})

最新更新