【问题标题】:How do I handle catching errors in multiple places in Angular stream?如何处理 Angular 流中多个位置的捕获错误?
【发布时间】:2021-11-27 17:30:51
【问题描述】:

现在我正在尝试确保我在首先获取组 id 的流中正确处理错误,然后使用该组 id 获取配置文件信息。

我需要它,因此很明显是哪个步骤导致了错误 - 获取 groupId 或获取配置文件信息。

现在我有这样的东西,但我不确定这是否正确。

this.groupRepository
    .getUserGroup()
    .pipe(mergeMap(group) => {
        return this.profileRepository.getAllProfiles(group.id)
    })
    .subscribe(
        (res) => {
            // doing things in here to set the groups and profiles
        },
        (error) => {
            this.error = error;
        }
    );

【问题讨论】:

  • 如果getUserGroup 会抛出错误然后getAllProfiles 调用将不会进行,则上面是正确的。如果您想在任何时候发生错误时继续流式传输,则可以使用 catchError 运算符 rxjs.dev/api/operators/catchError

标签: javascript angular error-handling rxjs


【解决方案1】:

你做得对。

两种方法的错误最终都会出现在(error) => {...} 方法中。

小测试:

of('A', 'B', 'C').pipe(mergeMap(letter => {
  return of('E', 'F', 'G');
})).subscribe(
    (res) => {
      console.log(res);
    },
    (error) => {
      console.log(error);
    }
  );

返回:'E'、'F'、'G'、'E'、'F'、'G'

使用第二种方法抛出:

of('A', 'B', 'C').pipe(mergeMap(letter => {
  return throwError('bad');
})).subscribe(
    (res) => {
      console.log(res);
    },
    (error) => {
      console.log(error);
    }
  );

返回:“坏”

第一个方法抛出:

throwError('bad').pipe(mergeMap(letter => {
  return of('E', 'F', 'G');
})).subscribe(
    (res) => {
      console.log(res);
    },
    (error) => {
      console.log(error);
    }
  );

返回:“坏”

【讨论】:

    猜你喜欢
    • 2019-05-23
    • 1970-01-01
    • 2018-02-19
    • 2012-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-30
    相关资源
    最近更新 更多