RxJ捕获错误并继续

时间:2016-07-29 02:31:09

标签: javascript rxjs reactivex

我有一个要解析的项目列表,但其中一个项目的解析可能会失败。

什么是" Rx-Way"捕获错误但继续执行序列

代码示例:



var observable = Rx.Observable.from([0,1,2,3,4,5])
.map(
  function(value){
      if(value == 3){
        throw new Error("Value cannot be 3");
      }
    return value;
  });

observable.subscribe(
  function(value){
  console.log("onNext " + value);
  },
  function(error){
    console.log("Error: " + error.message);
  },
  function(){
    console.log("Completed!");
  });

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.0.6/rx.all.js"></script>
&#13;
&#13;
&#13;

我想以非Rx方式做什么:

&#13;
&#13;
var items = [0,1,2,3,4,5];

for (var item in items){
  try{
    if(item == 3){
      throw new Error("Value cannot be 3");
    }
    console.log(item);
  }catch(error){
     console.log("Error: " + error.message);
  }
}
&#13;
&#13;
&#13;

提前致谢

4 个答案:

答案 0 :(得分:33)

我建议您使用flatMap(现在mergeMap在rxjs版本5中),如果您不关心它们,可以让您折叠错误。实际上,您将创建一个内部Observable,如果发生错误,可以吞下它。这种方法的优点是你可以将运算符链接在一起,如果管道中的任何地方发生错误,它将自动转发到catch块。

var observable = Rx.Observable.from([0, 1, 2, 3, 4, 5])
  .flatMap((value) =>          
    Rx.Observable.if(() => value != 3,
      Rx.Observable.just(value),
      Rx.Observable.throw(new Error("Value cannot be 3")))
    //This will get skipped if upstream throws an error
    .map(v => v * 2)
    .catch((err) => {
      console.log("Caught Error, continuing")
      //Return an empty Observable which gets collapsed in the output
      return Rx.Observable.empty();
    })
  );

observable.subscribe(
  (value) => console.log("onNext " + value), (error) => console.log("Error: " + error.message), () => console.log("Completed!")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.0.6/rx.all.js"></script>

答案 1 :(得分:24)

您需要切换到新的一次性流,并且如果在其中发生错误将安全地处置,并保持原始流存活:

&#13;
&#13;
Rx.Observable.from([0,1,2,3,4,5])
    .switchMap(value => {

        // This is the disposable stream!
        // Errors can safely occur in here without killing the original stream

        return Rx.Observable.of(value)
            .map(value => {
                if (value === 3) {
                    throw new Error('Value cannot be 3');
                }
                return value;
            })
            .catch(error => {
                // You can do some fancy stuff here with errors if you like
                // Below we are just returning the error object to the outer stream
                return Rx.Observable.of(error);
            });

    })
    .map(value => {
        if (value instanceof Error) {
            // Maybe do some error handling here
            return `Error: ${value.message}`;
        }
        return value;
    })
    .subscribe(
      (x => console.log('Success', x)),
      (x => console.log('Error', x)),
      (() => console.log('Complete'))
    );
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.4.1/Rx.min.js"></script>
&#13;
&#13;
&#13;

此博客文章中有关此技术的更多信息:The Quest for Meatballs: Continue RxJS Streams When Errors Occur

答案 2 :(得分:1)

要防止endlessObservable$死亡,可以将failingObservable$放在高阶映射运算符中(例如switchMapconcatMapexhaustMap。 。)并通过观察到empty()不返回任何值终止内部流来吞没该错误。

使用RxJS 6:

endlessObservable$
    .pipe(
        switchMap(() => failingObservable$
            .pipe(
                catchError((err) => {
                    console.error(err);
                    return empty();
                })
            )
        )
    );

答案 3 :(得分:0)

您实际上可以在地图功能中使用 try / catch 来处理错误。这是代码段

&#13;
&#13;
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!");
    });
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.0.6/rx.all.js"></script>
&#13;
&#13;
&#13;