handling errors with flatMapLatest and retry

410 views Asked by At

I have a web page where there are a bunch of items that the user can click on. clicking on any item, depending on it's type, will send an ajax request to the server and then display more items. If the request results in an error, I want to display it and then allow the user to continue clicking or interacting with the page as before.

My code looks like this

$scope.$createObservableFunction("clickHandler")
    .flatMapLatest(function (args) {
        //send the ajax request to the server
    })
    .retry()
    .subscribe(function (data) {
         //handle getting the data from the server
    })

where exactly can I handle the error case? I expect errors to happen, and I always want to re-subscribe to the source, but I want a chance to handle that error.

1

There are 1 answers

2
Brandon On BEST ANSWER

The trick is to turn your errors into data:

$scope.$createObservableFunction("clickHandler")
    .flatMapLatest(function (args) {
        //send the ajax request to the server
        var ajaxQuery = someObservable;

        // turn the observable into
        // a stream of eithers, which will
        // either have a 'result'
        // or an 'error'
        // use .catch() to turn the error
        // into a either with an error property
        // use .map() to turn the success
        // into a either with the result property
        return ajaxQuery
            .map(function (result) {
                return { result: result };
            })
            .catch(function (error) {
                return Rx.Observable.of({ error: error });
            });
    })
    .subscribe(function (data) {
         if (data.error) {
            // display data.error to user
         }
         else {
            // display data.result to user
         }
    })

If your ajax method returns a Promise, use then chaining:

$scope.$createObservableFunction("clickHandler")
    .flatMapLatest(function (args) {
        //send the ajax request to the server
        var ajaxQuery = somePromise;

        // turn the promise into
        // a promise of eithers, which will
        // either have a 'result'
        // or an 'error'
        return ajaxQuery
            .then(function onSuccess(result) {
                return { result: result };
            }, function onError (error) {
                return { error: error };
            });
    })
    .subscribe(function (data) {
         if (data.error) {
            // display data.error to user
         }
         else {
            // display data.result to user
         }
    })