在没有内部观察的情况下,如何处理NGRX效应中的错误?
考虑一个可以引发异常的正常功能:
function canThrow(){
...
throw 'error';
}
我想在ngrx效果中使用它:
public myEffect$ = createEffect(() =>
this.actions$.pipe(
ofType(DoSomethingAction),
map(() =>
canThrow(),
),
map(() => SucceededAction()),
catchError(() => of(FailedAction())),
),
);
但是,这会导致失败
被排放然后完成,这杀死了效果 - 类似于
cather> catcherror
不是从返回可观察到的函数中管道的。
这里 canthrow
dis 不是返回可观察的。
我该如何构建代码以便处理错误,但不会通过完成终止效果?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议使用
switchmap
canthrow
不返回可观察的操作员。 https://stackblitz.com/edit/redit/rxjs-mk5bla?file= index。 TS您可以在这里了解更多信息:
I recommend using a flattening operator like
switchMap
assumingcanThrow
does not return an observable. https://stackblitz.com/edit/rxjs-mk5bla?file=index.tsYou can learn more here: https://www.learnrxjs.io/learn-rxjs/operators/transformation/switchmap
我提出了两种实现这一目标的方法:
映射可以尝试/捕获而无需观察到
沿着亚历克斯的回答,这是一种使用
try..catch
的势在必行的方法switchmap
和返回的动作转换为可观察到的不需要:defer/of and catherror
更面向RXJS的解决方案,该解决方案可创建可观察的包装
canthrow 和管道响应,允许使用
catherror
:I came up with 2 ways of achieving this:
map to try/catch without observables
Along the lines of Alex's answer, a somewhat imperative approach using a
try..catch
but theswitchMap
and conversion of returned actions to observables is not required:switchMap with defer/of and catchError
A more rxjs oriented solution, which creates an observable wrapping
canThrow
and pipes the response which allows use ofcatchError
: