是否可以在不完成 Observable 流的情况下在 ngrx-effects 中抛出错误?

A.K*_*ger 2 error-handling ngrx ngrx-effects angular

有没有办法throw在 ngrx-effects 流中使用Error 对象而不完成流?

我已经阅读了这些关于为什么通过抛出错误杀死流的很好的答案:

@ngrx Effect 不会第二次运行

ngrx 效果错误处理

https://github.com/ngrx/platform/issues/646

我的问题是我是否正在实施 AngularErrorHandler来捕获错误,如果我能够将其与 ngrx 效果一起使用。

@Effect()
  loginUserEffect: Observable<loginActions.Actions> = this.actions$
    .ofType(loginActions.LOGIN_USER)
    .map((action: loginActions.LoginUser) => action.payload)
    .mergeMap(payload => {
      return this.loginService
        .authenticate(payload)
        .map(response => new loginActions.LoginUserSuccess(response))
        .catch((error: HttpErrorResponse) =>
          of(new loginActions.LoginUserFailure(error))
        )
  })

  @Effect({ dispatch: false })
  loginUserEffectSuccess$ = this.actions$
    .ofType(loginActions.LOGIN_USER_SUCCESS)
    .do(() => this.router.navigate(['/account-home']))

  @Effect({ dispatch: false })
  loginUserEffectFailure$ = this.actions$
    .ofType(loginActions.LOGIN_USER_FAILURE)
    .map((action: loginActions.LoginUserFailure) => {
      throw action.payload // Stream completes
  })
Run Code Online (Sandbox Code Playgroud)

我想我可以创建一些不涉及抛出任何错误的方法来处理错误,但想确保我需要走那条路,或者是否有办法让两者和平共处。

目前在我实现的班级中ErrorHander,我有这个:

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
  private messagesService: MessagesService
  private router: Router

  constructor(
    private injector: Injector, // DI workaround (/sf/answers/2911013171/)
    private errorLoggerService: ErrorLoggerService
  ) {
    // DI workaround (/sf/answers/2911013171/)
    setTimeout(() => (this.messagesService = injector.get(MessagesService)))
    setTimeout(() => (this.router = injector.get(Router)))
  }

  handleError(error) {
    if (error instanceof HttpErrorResponse) {
      this.handleServerError(error)
    } else if (error instanceof ClientError) {
      this.handleClientError(error)
    } else {
      this.handleUnexpectedError(error)
    }
  }
Run Code Online (Sandbox Code Playgroud)

这意味着我只是抛出错误并根据类型处理它们

A.K*_*ger 5

我最终创建了一个错误操作:

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

并在专用效果中调用错误处理程序:

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

我离开全局错误处理程序只是为了捕获和记录意外异常。