【问题标题】:How to catch @ngrx/effects errors properly?如何正确捕获@ngrx/effects 错误?
【发布时间】:2020-01-03 11:52:18
【问题描述】:

我知道这个问题已经被问过好几次了,但请记住我的具体问题,因为我找不到任何可以正确解决它的方法。

我有一个effect,它应该按特定顺序执行多个 HTTP 请求 - 调用 1、调用 2、调用 3。我希望能够捕获任何错误连锁,链条。我想保持rxjs 运算符的结构尽可能平坦,以避免嵌套意大利面条代码。

这里是示例代码:

getMockDataEffect$ = createEffect(
    () => this.actions$.pipe(
      ofType(ApiGetMockData),
      concatMap(() => {
        return this.mockApi.mock1().pipe(
          concatMap(() => {
            return this.mockApi.mock2();
          }),
          concatMap(() => {
            return this.mockApi.mock3();
          }),
          map(res => ApiSuccess({ data: res })),
          catchError(error => of(ApiError({ error }))),
        )
      }
      )
    )
  )

在上面给出的示例中,如果mock2mock3 中出现错误,则会成功捕获。但是,如果出现在mock1 中,则根本不会捕获该错误。

我的问题是:我如何构建我的效果,使我的catchError 运算符能够捕捉到mock1mock2mock3 中发生的任何错误,没有完成效果的 observable?意思是,如果发生错误,我应该能够派发动作并在此之后成功运行效果。

这是StackBlitz demo

【问题讨论】:

    标签: angular error-handling rxjs ngrx-effects


    【解决方案1】:

    我认为你的例子很好。

    问题是throw,因为我认为这是为了执行 JavaScript,它只是停止,因为它没有被捕获。

    实际情况是函数以 Observable 格式返回错误,为此您必须使用 throwError。当一个 http 请求失败时,将会是一个可观察到的错误。

    因此,为了让您的情况正常,请将mockapi.service.ts 更改为以下内容:

    import { Injectable } from '@angular/core';
    import { of, throwError } from 'rxjs';
    import { map, tap } from 'rxjs/operators';
    
    @Injectable({ providedIn: 'root' })
    export class MockApiService {
    
      mock1() {
        //return throwError('e1');
        return of('mock1');
      }
    
      mock2() {
        // return throwError('e2');
        return of('mock2');
      }
    
      mock3() {
        // return throwError('e3');
        return of('mock3');
      }
    }
    

    取消注释任何throwErrors 上的任何模拟函数出错。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-17
      • 1970-01-01
      • 1970-01-01
      • 2021-07-26
      • 1970-01-01
      相关资源
      最近更新 更多