RxJs catch error and continue

后端 未结 4 944
臣服心动
臣服心动 2020-12-08 08:58

I have a list of items to parse, but the parsing of one of them can fail.

What is the \"Rx-Way\" to catch error but continue executing the sequence

Code Samp

4条回答
  •  温柔的废话
    2020-12-08 09:51

    You can actually use try/catch inside your map function to handle the error. Here is the code snippet

    var source = Rx.Observable.from([0, 1, 2, 3, 4, 5])
        .map(
            function(value) {
                try {
                    if (value === 3) {
                        throw new Error("Value cannot be 3");
                    }
                    return value;
    
                } catch (error) {
                    console.log('I caught an error');
                    return undefined;
                }
            })
        .filter(function(x) {
            return x !== undefined; });
    
    
    source.subscribe(
        function(value) {
            console.log("onNext " + value);
        },
        function(error) {
            console.log("Error: " + error.message);
        },
        function() {
            console.log("Completed!");
        });

提交回复
热议问题