【问题标题】:How can I catch a timeout request如何捕获超时请求
【发布时间】:2018-07-10 14:06:27
【问题描述】:

这是我的代码:

properties.service.ts

get(stringParams) {
    let headers = new Headers({
      "X-AUTH-APIKEY":  API_KEY
    });

    this.options = new RequestOptions({
      headers: headers
    });
    return this.http
      .get(`${API_URL}/properties/?${stringParams}`, this.options)
      .timeout(50)
      .map((response: Response) => response.json())
  }



posts.ts

    this.propertiesService.get(arrayParams).subscribe((data: any) => {

    }), (err) => { console.log("timeoout")};

我在超时时设置了 50,因此被解雇,但我无法以这种方式捕获错误

}), (err) => { console.log("timeoout")};

我收到此错误:

TimeoutError {name: "TimeoutError", stack: "TimeoutError: Timeout has occurred↵    at new Time…http://localhost:8100/build/polyfills.js:3:10143)", message: "Timeout has occurred"

编辑:

this.propertiesService.get(arrayParams).subscribe((data: any) => {

        }), (err) => { console.log("timeoout")};

get(stringParams) {

    return this.http
      .get(`${API_URL}/properties/?${stringParams}`, this.options)
      .timeout(50)
      .map((response: Response) => response.json())
      .catch(this.handleError);
}

private handleError(error: any) { 
  return Observable.throw(error);
}

我尝试了这个解决方案,但我仍然收到此错误

解决方案:

代码应该是这样的(订阅中的错误):

}, (err) => { console.log("timeoout")});

【问题讨论】:

  • 所以您在设置的 50 毫秒内没有得到响应。您期待什么错误?
  • 我期待 console.log("timeoout") 但我得到了我上面描述的错误

标签: javascript angular ionic2 ionic3


【解决方案1】:

err 应该在 subscribe

this.propertiesService.get(arrayParams).subscribe((data: any) => {

    }, (err) => { console.log("timeoout")});

你应该catch例外:

get(stringParams) {

    return this.http
      .get(`${API_URL}/properties/?${stringParams}`, this.options)
      .timeout(50)
      .map((response: Response) => response.json())
      .catch(this.handleError);
}

private handleError(error: any) { 
  return Observable.throw(error);
}

【讨论】:

  • @FrancoCoronel 由于我公司的互联网限制,我看不到 SO 中的图像。但是你能像我的回答一样移动 par err 吗?因为它可能会导致问题。您的部分错误不在订阅范围内
  • 你是对的,我在订阅之外有错误,这是错误。谢谢
猜你喜欢
  • 2012-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-26
  • 1970-01-01
  • 2013-05-08
相关资源
最近更新 更多