RxJS error handling

2.6k views Asked by At

I've got an issue with RxJS swallowing errors. So in my case I've got something like this:

function funcThatThrowsError(fn, ..args) {
     return fn.bind(fn, ...args);
}

function fetchItems() {
     Observable.fromPromise(
        reqwest({
            url: `${API_ROOT}${url}`,
            method,
            data,
            contentType: "application/json"
        })
    ).map(funcThatThrowsError(null, "someValue"))
}

const observableA = fechItems();
const observableB = ... ;

Observable
    .combineLatest(
        observableA,
        observableB,
        () =>  { }
    )
    .forEach(
        () => { }, // success
        (err) -> console.log(err.stack);
    )

So basically I'm deliberately passing a null value as the fn parameter which causes the funcThatThrowsError to throw an exception.

The problem is that the error callback is not invoked in this case. Rather RxJS will use it's own thrower function

function thrower(e) {
   throw e;
}

What's the best practise to deal with this scenario. I feel that there is something that I'm missing.

1

There are 1 answers

0
paulpdaniels On BEST ANSWER

The exception is happening outside of the Observable. You are raising it while creating a function that you want to pass into the observable.

If you want the error handler at the end of the chain to handle it, you have to raise it inside of the operator chain:

function fetchItems() {
     Observable.fromPromise(
        request({
            url: `${API_ROOT}${url}`,
            method,
            data,
            contentType: "application/json"
        })
    ).map(funcThatThrowsError(content => throw new Error(content), "someValue"))
}