Is it possible to throw errors inside ngrx-effects without completing the Observable stream?

夙愿已清 提交于 2019-12-06 05:45:37

If you want to throw an error that will not be caught by the observable and will instead be reported to a global error handler, you have throw the error from outside of the observable's call stack.

You could do something like this:

@Effect({ dispatch: false })
loginUserEffectFailure$ = this.actions$
  .ofType(loginActions.LOGIN_USER_FAILURE)
  .do(action => setTimeout(() => { throw action.payload; }, 0))
})

However, as your effects are in a class that already uses Angular's DI mechanism, I would suggest you instead inject your GlobalErrorHandler and call it directly.

Without the setTimeout calls I think it would be clearer and easier to test, too.

I ended up creating an Error action:

@Effect()
  loginUserEffectFailure$: Observable<
    errorsActions.Actions
  > = this.actions$
    .ofType(loginActions.LOGIN_USER_FAILURE)
    .map(
      (action: loginActions.LoginUserFailure) =>
        new errorsActions.Error(action.payload)
    )

and having that call the error handler in a dedicated effect:

@Effect({ dispatch: false })
  errorEffect$ = this.actions$
    .ofType(errorsActions.ERROR)
    .map((action: errorsActions.Error) =>
      this.clientErrorHandler.handleError(action.payload)
    )

I left the global error handler just for unexpected exceptions to be caught and logged.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!