重试后如何捕获? [英] How to get catch after retryWhen?

查看:56
本文介绍了重试后如何捕获?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想重试几次 get 请求,并在出现错误时延迟第二次,但如果所有尝试都失败,则执行错误处理程序.

I want to retry get request a few times with a second delay in case of error, but if all attemps failed, then execute error handler.

以下代码重试请求,但从未执行 catch.我该如何解决?

Following code retryes request, but catch is never executed. How can I fix it?

import {Response, Http} from '@angular/http';
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

this.http.get("/api/getData").map(data => {
  console.log('get')
  return data.json()
})
.retryWhen(err => {
  console.log('retry')
  return err.delay(1000).take(5)
})
.catch(err => {
  console.log('catch')
  this.handleHttpError(err)
  return err
})
.subscribe(data => {
  console.log('subscribe')
  console.log(data)
})

推荐答案

这里的问题是当retryWhen中回调返回的通知Observable发送complete通知它作为 complete 进一步传播,这不是您想要的描述.

The problem here is that when the notification Observable returned from the callback in retryWhen sends the complete notification it's propagated further as complete which is not what you want from your description.

您想将其作为 error 通知发送,这意味着您不能使用 take() 并使用其他运算符重新抛出错误.

You want to send it as error notification which means you can't use take() and use some other operator to rethrow the error.

例如像这样:

Observable.defer(() => Observable.throw("It's broken"))
  .retryWhen(err => {
    console.log('retry');
    let retries = 0;
    return err
      .delay(1000)
      .map(error => {
        if (retries++ === 5) {
          throw error;
        }
        return error;
      });
  })
  .catch(err => {
    console.log('catch');
    return Observable.of(err);
  })
  .subscribe(data => {
    console.log('subscribe');
    console.log(data);
  });

您可以自己计算 retries 变量中的重试次数,如果达到某个限制,只需重新抛出错误.map() 运算符用 try-catch 块包装所有回调,因此在其可调用对象中抛出的任何错误都将作为 error 信号发送.

You can count the number of retries in the retries variable yourself and if it reaches some limit just rethrow the error. The map() operator wraps all callbacks with try-catch blocks so any error thrown in its callable is going to be sent as error signal.

这篇关于重试后如何捕获?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆