stashko
stashko

Reputation: 43

Catching errors in Promise, Observable.fromPromise() and subscribtion

Long story short: I'm not sure what kind of errors should be catched in fromPromise().catch() method and what errors should be resolved in onError(error: Error) observer's method.

I use node.js with rxjs, that's why I'm converting my promises to observables.

Take a look at the classic Promise definition

const getPromise = (target) => {
    return new Promise((resolve, reject) => {
        request(
            {
                url: url,
                json: true
            },
            (error, response, body) => {
                if (error) {
                    reject({
                        id: id,
                        error: error,
                        response: response,
                        body: body
                    });
                } else {
                    resolve({
                        id: id,
                        body: body
                    });
                }
            }
        );
    });
};

I'm converting my promises in the loop and returning observable array

const observableItems = [];
targetList.forEach((target) => {
  const observableItem = {
    id: target.id,
    observable$: rx.Observable
      .fromPromise(getPromise(target))
      .catch((error) => {
        // [1]
        return rx.Observable.of(error);
      })
  };
  observableItems.push(observableItem);
});

return observableItems;

And then I subscribe to my observables

observableItems.forEach((observableItem) => {
  const currentSubscribtion = observableItem.observable$.subscribe(
    (payload) => {
      if (payload && payload.error) {
        handleInvalidPayload(payload);
      } else {
        handleValidPayload(payload);
      }
    },
    (error) => {
      // [2]
    }
  );
  subscribtions.push(currentSubscribtion);
});

My questions:

1/ Is it possible to throw an error from [1] and pass it directly to the point [2]? At this moment I got if statement in onNext() - I don't like it.

I tried to use return Observable.throw(someObject) in catch() method without any success.

2/ What kind of errors should be resolved in catch() and in OnError() method?

I'm asking about connection timeouts, ENOTFOUND and backend errors with codes like 404?

Upvotes: 3

Views: 10553

Answers (1)

OJ Kwon
OJ Kwon

Reputation: 4641

Purpose of catch operator is to handle upstream errors and substitute desired value into observer::next (or re-throw if needed).

for cases like

Is it possible to throw an error from [1] and pass it directly to the point [2]?

, it seems you'd like to handle error in error observer directly. Which means you don't need to catch it, let rejection throws to error observer. Consider simple code snippet rejects immediately

const p = new Promise((res, rej) => rej(0));

Rx.Observable.fromPromise(p)
  .subscribe((x) => {}, (e) => console.log(e)); //0

next observer won't be called.

as said above, catch operator provieds mechanism to substitute errors as you want. say your rejected value is something you'd like to handle internally and pass forward, then you may return some values in catch to observer. It depends on nature of error you'd like to deal with, if you want to terminate observable stream with errored condition, you may not need catch it.

Upvotes: 2

Related Questions