Chris Bao
Chris Bao

Reputation: 2868

RxJS HTTP request error handling

In my project, I use RxJS to handle HTTP request. I came into a confusing point about the error handling part as following:

    .switchMap((evt: any) => {
      return http.getComments(evt.params)
        .map(data => ({ loading: false, data }))
        .catch(() => {
          console.log('debugging here');
          return Observable.empty();
        });
    })

in the above code, inside the switchMap operator, I use the http.getComments function to send request, which is defined by myself as following:

  getComments(params) {
    return Observable.fromPromise(
      this.io.get(path, { params })
    );
  }

in this function, I use fromPromise operator convert the returned Promise to observable.

The problem is when HTTP request failed, the catch operator inside switchMap can not work, the debugging console can't output. So what's wrong with my code.

Upvotes: 0

Views: 1352

Answers (2)

nicowernli
nicowernli

Reputation: 3348

Do you really need to catch the error inside the switchMap anyway? You can handle your error in your source if you want.

.switchMap((evt: any) => 
    http.getComments(evt.params).map(data => ({ loading: false, data }))
})
.subscribe(console.log, console.error);

Any way, your source code does not look to have any error, maybe your promise is not been rejected when the http fails and is just resolving with an error as a response (this is a guess because I've seen that before)

Upvotes: 1

Picci
Picci

Reputation: 17752

Your code should work. Here a simplified simulation, where http calls are substituted by a function which raises an error.

import {Observable} from 'rxjs';


function getComments(params) {
    return Observable.throw(params);
}

const params = 'abc'; 

Observable.of(null)
.switchMap(_ => {
    return getComments(params)
      .map(data => ({ loading: false, data }))
      .catch(err => {
        console.log('debugging here', err);
        return Observable.empty();
    });
})
.subscribe(
    console.log,
    error => console.error('This method is not called since the error is already caught', error),
    () => console.log('DONE')
)

Upvotes: 0

Related Questions