RxJS catchError 运算符不会捕获从 Promise 创建的可观察对象的错误

RxJS catchError operator does not catch an error on an observable created from a Promise

我正在使用 rxjs 6.5.1 构建 ionic 4 / angular 8 应用程序。

在这里,我有一个 Promise,它被转换为一个可观察的对象,该对象在管道中进一步使用,以便通过 ionic 的文件插件下载文件。如代码底部所示,我创建了一个 observable 数组,如果设置了 someFlag,将订阅该数组。此代码的问题在于,在将可观察对象推送到数组时,getLocationForFile(fileName) 中的代码被执行,我在控制台中收到以下错误:

ERROR Error: Uncaught (in promise): FileError: {"code":12,"message":"PATH_EXISTS_ERR"}。如果路径存在,这种错误完全可以发生。问题是这个错误没有被 getLocationForFile 方法的 catchError 运算符捕获。有趣的是,如果设置了 someFlag,将触发 forkJoin,然后在 getLocationForFile(fileName) 的 catchError 中捕获完全相同的错误,但未捕获的承诺错误的错误仍然存​​在。

private createDirectory(dirName) {
    return from(this.file.createDir(path, dirName))
}

public getLocationForFile(fileName: string) {
    return  this.createDir().pipe(
      switchMap(dirEntry => of(dirEntry.nativeURL + fileName)),
      catchError(_ => of(""))
    )
}

public downloadFile(fileName) {
    return this.getLocationForFile(fileName).pipe(
        switchMap(fileLocation => return this.file.downloadFile(url, {}, {}, fileName)),
        catchError(error => of(handleError(error));
    )
}

let filesToDownload = [];

for(let fileName of fileNames) {
    filesToDownload.push(downloadFile(fileName))
}

if(someFlag){
    forkJoin(filesToDownload).subscribe(results => {
        handleResults(results)
    })
}

以防我像这样重写 createDirectory(dirName)

private createDirectory(dirName) {
    return from(this.file.createDir(path, dirName)
    .then(result => of(result))
    .catch(error => throwError(error))
    )
}

然后错误得到处理,我没有得到 Uncaugh in promise 错误。

所以一个问题是为什么 createDirectory 方法中的 catchError 没有捕捉到当我将 observable 推送到数组时发生的错误,另一个问题是如何修复它(我不想使用最后一个代码片段中的解决方法)。

谢谢!

也许先修复您的承诺代码会解决您的问题

不用catch,让error流过

private createDirectory(dirName) {
    return defer(()=>this.file.createDir(path, dirName))
}