简体   繁体   中英

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

I am building an ionic 4 / angular 8 app using rxjs 6.5.1.

Here I have a Promise that is converted to an observable that is used further down the pipe in order to download a file via a file plugin for ionic. As seen at the bottom of the code, I create an array of observables, which will be subscribed to in case someFlag is set. The issue with this code is that at the point of pushing the observables to the array, the code in getLocationForFile(fileName) gets executed and I get the following error in the console:

ERROR Error: Uncaught (in promise): FileError: {"code":12,"message":"PATH_EXISTS_ERR"} . Such error is perfectly fine to happen in case the path exists. The problem is that this error is not caught in the catchError operator of the getLocationForFile method. The interesting part is that in case someFlag is set, the forkJoin will be triggered and the very same error will be then caught in the catchError in getLocationForFile(fileName), but the error of uncaught promise error will still be there.

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)
    })
}

In case I rewrite the createDirectory(dirName) like this

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

then the error is handled and I do not get the Uncaugh in promise error.

So one question is why the catchError in the createDirectory method does not catch the error that occurs when I push the observable to the array and the other one is how to fix it (I do not want to use the workaround from the last code snippet).

Thanks!

Maybe fix your promise code first will solve your problem

there is no need to catch, let the error flow through

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM