Aurelia中fetch()的错误处理

AR.*_*AR. 16 javascript fetch aurelia aurelia-fetch-client

我有一个API,其中包含服务器引发错误时出错的有用描述(状态= 500).该描述作为响应文本的一部分.我的客户端代码,使用Aurelia,通过aurelia-fetch-client使用通用方法调用api 来进行调用:

function callRemoteService(apiName, timeout) {
  return Promise.race([
    this.http.fetch(apiName),
    this.waitForServer(timeout || 5000)  // throws after x ms
  ])
    .then(response => response.json() )
    .catch(err => {
        if (err instanceof Response) {
          // HERE'S THE PROBLEM.....
          err.text().then(text => {
            console.log('Error text from callRemoteService() error handler: ' + text);
            throw new Error(text)
          });
        } else if (err instanceof Error) {
          throw new Error(err.message);
        } else {
          throw new Error('Unknown error encountered from callRemoteService()');
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

请注意,我想以一致的方式捕获服务器(获取或超时)错误,然后throw只返回一个简单的错误消息到调用视图.我可以callRemoteService成功调用,在返回500时捕获错误:

callRemoteService(this.apiName, this.apiTimeout)
  .then(data => {
    console.log('Successfully called \'' + this.apiName +
      '\'! Result is:\n' + JSON.stringify(data, null, 2));
    })
  .catch(err => {
    console.log('Error from \'' + this.apiName + '\':',err)
    });
Run Code Online (Sandbox Code Playgroud)

但是,我在访问响应文本时遇到了问题,因为它fetch提供了text()返回promise 的方法,并且这干扰了我本来很开心的承诺链接.上面的代码不起作用,给我一个Uncaught (in promise)错误.

希望有一种很好的方式来访问该响应文本?

Jer*_*yow 12

这应该做的伎俩:

function callRemoteService(apiName, timeout = 5000) {
  return Promise.race([
    this.http.fetch(apiName)
      .then(
        r => r.json(),
        r => r.text().then(text => throw new Error(text))
      ),
    this.waitForServer(timeout)
  ]);
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,我喜欢你正在做的事Promise.race- 很棒的技巧!

  • 但是它使请求保持打开状态并且待定,对吧?这样好吗? (2认同)
  • 哦 - 我看到 - 如果发生超时,请求仍然处于待处理状态.不好,但没有答案,直到他们在规范中解决问题.https://github.com/whatwg/fetch/issues/20 https://github.com/whatwg/fetch/issues/27 (2认同)