0

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.

1
  • Why catch cannot work inside switchMap? Commented Mar 22, 2018 at 12:04

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.