首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如果请求返回错误,如何使用不同的url重试

如果请求返回错误,如何使用不同的url重试
EN

Stack Overflow用户
提问于 2021-05-02 07:28:19
回答 3查看 70关注 0票数 0

我有一个看起来像这样的请求:

代码语言:javascript
运行
复制
  private getData(param) {
    const url = (name: string) =>
      `https://website.com/${name}/data`;

    return this.http.get<Data>(url(param));
  }

当请求返回一个错误时,我想用另一个参数重试。你怎么能这样做呢?

我能够捕捉到这样的错误

代码语言:javascript
运行
复制
  private getData(param) {
    const url = (name: string) =>
      `https://website.com/${name}/data`;

    return this.http.get<Data>(url(param)).pipe(
       catchError(error => of(error))
    );
  }

但是如何用不同的url重试呢?

EN

回答 3

Stack Overflow用户

发布于 2021-05-02 08:01:57

catchError的返回值为observable。如果只想发出新请求,可以用新请求替换可观察到的错误。就像这样。

代码语言:javascript
运行
复制
const example = source.pipe(
  catchError(val => {
    return of(`new request result`)
  }));
//output: 'new request result'
const subscribe = example.subscribe(val => console.log(val));
票数 2
EN

Stack Overflow用户

发布于 2021-05-02 07:51:18

不知道,但你能这样试一下吗?

代码语言:javascript
运行
复制
 private getData(param) {
    const url = (name: string) =>
      `https://website.com/${name}/data`;
     const anotherUrl = (name: string) =>
      `https://website.com/${name}/data`;

    return this.http.get<Data>(url(param)).pipe(
       catchError(error => of(error){
            this.http.get<Data>(anotherUrl(param)).pipe(
              catchError(error => of(error))
       })
    );
  }
票数 1
EN

Stack Overflow用户

发布于 2021-05-02 12:47:01

如果我是你,我会这样尝试。

代码语言:javascript
运行
复制
class UserService {
  private getData(param, tried=3) {
    const url = (name: string) => {
      `https:///website.com/${name}/data`;
    }

    return this.http.get<Data>(url(param)).pipe(catchError(error => {
      if (tried < 0) {
        throw error;
      }
      // assign name, param's property as a new value
      param.name = 'newName';
      // then, call again with param with another name 
      // while tried counter to be 0
      this.getData(param, tried - 1);
    }));  
  }
}

  1. 将新参数tried添加到getData方法,以处理无限循环的重试。并将其缺省值设置为3(可能是5、7,其他您喜欢的值),并使用您的方法,如果此请求出错,请使用NestJS.pipe.
  2. Then的http方法,重试使用另一个名称更新的参数,如分配我编写的param.name = 'newName'
  3. 使用tried参数中的dicsount -1递归调用此getData方法。<代码>H217<代码>G218

愿这对你有所帮助。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67351713

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档