Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 : Error handling with forkJoin

Tags:

angular

rxjs

I am not sure how to get exception message for specific api call while using forkJoin

I have code written as below

    reqs = [];
    if (shouldUpdatePhone) {
       reqs.push(this.customerService.updatePhone(phoneUpdateRequest))
    }
    if (shouldUpdateAddress) {
       reqs.push(this.customerService.updateAddress(addressUpdateRequest))
    }

    forkJoin(reqs).subscribe(result => {
       console.log('result :', result);

    }, error => {
      //How to get error message for particular api call?
});

In case one/both api failed due to some reason. How should i decide which api throws an exception.

like image 653
tt0206 Avatar asked Aug 23 '18 20:08

tt0206


1 Answers

You can't since forkJoin will throw an error on the first error it encounters from any of the observables. If there's not something in the error that is emitted that tells you were it came from such as checking an error code, you have the option in handling the error when creating the observable from the service call.

reqs = [];
if (shouldUpdatePhone) {
   reqs.push(
     this.customerService.updatePhone(phoneUpdateRequest).pipe(catchError(() => {
       throw 'phoneUpdateError';
     });
   )
}
if (shouldUpdateAddress) {
   reqs.push(
     this.customerService.updateAddress(phoneUpdateRequest).pipe(catchError(() => {
       throw 'addressUpdateError';
     });
   )
}

Now you can check which error has been thrown. You don't have to do this with error handling though; you could also map the error to a successful response and handle that.

Ultimately I would recommend combining these API calls.

like image 53
Explosion Pills Avatar answered Oct 25 '22 15:10

Explosion Pills