sebba23
sebba23

Reputation: 574

how to catch error when api call fails in angular 2

I'm developing an app that scans qr codes. I have a service dedicated to the scanner device where I get the data scanned.

this.dataWedge.scanResult$
      .pipe(
        tap(_ => (this.scanning = false)),
        filter(_ => this.assignState.getAssign() === this.assignState.Default),
        switchMap(scanData =>
          this.api.callApi(
            PurchaseOrderQuery,
            {
              DataString: scanData.DataString
            }
          )
        )
      )
      .subscribe(purchaseOrder => {
        this.scannedResult$.next(purchaseOrder);
      });

The problem is that when I pass a datastring that doesn't exist in the database, the api call fails (as it should be), but it never goes in the subscribe. How can I catch the error response from the api when this fails? Is it because of the switchMap maybe?

Upvotes: 0

Views: 123

Answers (2)

user4676340
user4676340

Reputation:

Subscriptions have three callbacks :

xxx().subscribe(
  response => { ... }, // Request completed
  error => { ... }, // Request error
  () => { ... }, // Triggered in any case (like a "finally" from a try-catch block)
);

This is how you manage errors.

You can also keep your stream going with catchError :

xxx().pipe(
  catchError(err => of('some value')),
);

This will continue the stream with "some value" instead of the value of your stream.

Upvotes: 1

Yash Rami
Yash Rami

Reputation: 2317

here it an example

     this.dataWedge.scanResult$
     .pipe(
     tap(_ => (this.scanning = false)),
     filter(_ => this.assignState.getAssign() === this.assignState.Default),
     switchMap(scanData =>
       this.api.callApi(
        PurchaseOrderQuery,
        {
          DataString: scanData.DataString
        }
      )
     )
    )
    .subscribe(purchaseOrder => {
     this.scannedResult$.next(purchaseOrder);
    }, err {
           console.log(err); // here you will get the error if api call fails 
    });

Upvotes: 1

Related Questions