首页 文章

Aurelia中fetch()的错误处理

提问于
浏览
15

我有一个API,其中包含服务器引发错误时出错的有用描述(status = 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()');
        }
    });
}

请注意,我想以一致的方式捕获服务器(获取或超时)错误,然后 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)
    });

但是,我在访问响应文本时遇到问题,因为 fetch 提供了返回promise的 text() 方法,并且's interfering with my otherwise happy promise chaining. The code above doesn' t工作,给我留下了 Uncaught (in promise) 错误 .

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

1 回答

  • 11

    这应该是诀窍:

    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)
      ]);
    }
    

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

相关问题