Search code examples
angularionic-frameworkrxjsionic4rxjs-pipeable-operators

Exception Handling in Angular Chained Methods?


I have a simple question & I think that would be easy to answer for Angular Experts.

I have a method like below:

 private uploadPicture(imagePath: string, apiUrl: string): Observable<ApiResponse<string>> {

   return this.convertFileFromFilePathToBlob(imagePath).pipe(
      switchMap(item => this.convertBlobToFormData(item)),
      switchMap(formData => this.postImageToServer(formData, apiUrl)),
      catchError((error: any) => {
        if (error instanceof Response) {
            return throwError(new AppError(error));
        } else {
            return throwError(new AppError(null, 'Error occured at convertFileFromFilePathToBlob.'));
        }
      })
    );
  }

I have chained 3 methods in one method:

  1. convertFileFromFilePathToBlob
  2. convertBlobToFormData
  3. postImageToServer

All 3 methods can raise/emit error at any point of failure. My question is about how to do exception handling in such cases?

Is my current implementation, having only one catchError is fine? If fine, will it be executed if any of the chained methods raise an error?

or

Do I need to use multiple catchError operators after each method to catch its error? If yes, I don't know how can I do that?

Can someone please explain how should I handle error in such cases?


Solution

  • You can have only one catchError, which should be enough. But make sure its at the end of all other operators. Because it catches error, replaces the stream, and hence allowing stream to continue. For example refer the below bubble diagram.

    enter image description here

    RxJS documentation on catchError

    Angular University post


    In your case, I do not see a reason to use catchError, you can just use Observable's error handling. .subscribe takes a second parameter as error handling function.