1

我写了一个代码,我想在发生异常时捕获错误:

this.assetApiService.getAssets(new AssetSearchCriteriaDto({tags: [AssetTags.tenant]})).pipe(
          catchError(error => {
           console.log(error);
          }),
          (mergeMap((assets: AssetDto[]) => {
                this.appInitStorageService.setAvailableTenants(assets);
                return this.userApiService.getUserById(this.authApiService.getAuth().userInfo.id);
              }
            )
          )
        )
          .subscribe((user: UserDto) => {
            this.persistSelectedUserLanguage(user);
            this.appInitStorageService.setUser(user);
            resolve();
          }, error => {
            console.log('error:', error);
          });

目标是捕获错误,如果它们发生在序列中的第一个可观察对象(getAssets)或第二个可观察对象(getUserById)中。我在第一个中添加了 catchError 运算符,但我看不到 console.log(error)。我不知道为什么。在此示例中,我应该如何正确捕获错误?

4

2 回答 2

0

你可以移动catchError下面的mergeMap来捕捉两个可观察对象的错误。同样重要的是要记住catchError 必须返回一个可观察的。你可以使用 RxJSthrowError函数抛出一个可观察到的错误

this.assetApiService.getAssets(new AssetSearchCriteriaDto({tags: [AssetTags.tenant]})).pipe(
  mergeMap((assets: AssetDto[]) => {
    this.appInitStorageService.setAvailableTenants(assets);
    return this.userApiService.getUserById(this.authApiService.getAuth().userInfo.id);
  }),
  catchError(error => {
    console.log(error);
    return throwError(error); // return error that will trigger the subscriptions `error` block
  })
).subscribe({
  next: (user: UserDto) => {
    this.persistSelectedUserLanguage(user);
    this.appInitStorageService.setUser(user);
    resolve();
  }, 
  error: error => {
    console.log('error:', error);
  }
});

另一方面,如果您希望将错误转换为有效排放并因此保持流运行而不是出错,您可以使用 RxJSof函数。错误将被发送到订阅的next回调而不是error回调

this.assetApiService.getAssets(new AssetSearchCriteriaDto({tags: [AssetTags.tenant]})).pipe(
  mergeMap((assets: AssetDto[]) => {
    this.appInitStorageService.setAvailableTenants(assets);
    return this.userApiService.getUserById(this.authApiService.getAuth().userInfo.id);
  }),
  catchError(error => {
    console.log(error);
    return of(error); // return error that will trigger the subscriptions `next` block
  })
).subscribe({...});
于 2020-11-16T10:52:51.503 回答
0

你的代码在编译吗?您必须在以下位置返回 Observable catchError

catchError(error => {
    console.log(error);
    return of([ ]);
}),

这样,流可以在捕获错误后继续处理。如您所见catchError,只有可以恢复控制流才有意义 - 否则错误可能会冒泡到订阅错误处理程序。一个很大的区别是,如果错误到达订阅,observable 将停止发射,而catchError它将继续发射(这与您的情况无关,但例如在 an intervalor fromEventObservable 发射多个值的情况下)。

如果这不能解决您的问题,请确保它this.assetApiService.getAssets实际上引发了异常。也许它只是出于某种原因返回带有错误响应代码的响应?

于 2020-11-16T10:59:53.900 回答