29er
29er

Reputation: 9035

RXJS throw error in a fromPromise does not hit 'catchError' piped method

Can someone explain why this promise (runQuery) , which fails into the 'catch' and throws an ErrorObservable, does not get caught in the 'catchError' method, but goes into 'map' method.
( I tried both _throw/ErrorObservable approach, same result )

import { _throw } from 'rxjs/observable/throw';
import { ErrorObservable } from 'rxjs/observable/ErrorObservable';

const runQuery = ( Promise that rejects )

const source$ = fromPromise(
  runQuery({ d: 'g' })
    .catch(err => {
      return new ErrorObservable(err);
      //return _throw(err); -- same as above
    })
  )
  .pipe(
    map((response: any) => {
      //ENTERS HERE as response.error     
    }),
    catchError(e => {
      //DOES NOT ENTER
    })
  );

Upvotes: 3

Views: 3719

Answers (3)

Renato Probst
Renato Probst

Reputation: 6054

If you want to change the error object or do a console.log() inside the catch in the promise before the observable receives the error you can throw the error:

.then(data => {
  return data;
})
.catch(err => {
  console.error("Error", err );
  err.code = 110; // you may want to change something before passing to observable
  throw err;
}))

If you use return error the error or catch pipe of the observable won't work, but using throw it works.

Upvotes: 0

Luillyfe
Luillyfe

Reputation: 6872

I made a live example to prove my point. There is no need to handle the promise (when it is still a promise), so this far from recommendable.

.then(data => {
  return data;
})
.catch(err => {
  return new ErrorObservable(err);
  //return _throw(err); -- same as above
}))

Let observables take control of rejections

const source$ = fromPromise(runQuery())        
    .pipe(
        map((response: any) => {
            //Make here some transformations
            return response;     
        }),
        catchError(e => {
            return _throw(e);
        }
    ));

Upvotes: 1

Mark van Straten
Mark van Straten

Reputation: 9425

You are handling your own error in the promise and let it return an ErrorObservable. By doing so you made the promise succeed (although with an error like return value). fromPromise will convert this in an emission instead of error.

Remove the catch case in the fromPromise and it should hit the Observable.catchError

Upvotes: 2

Related Questions