gpt4 book ai didi

javascript - Aurelia 中 fetch() 的错误处理

转载 作者:可可西里 更新时间:2023-11-01 01:25:06 24 4
gpt4 key购买 nike

我有一个 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()');
}
});
}

请注意,我想以一致的方式捕获服务器(获取或超时)错误,然后throw 仅向调用 View 返回一条简单的错误消息。我可以成功调用 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() 方法,这干扰了我本来很高兴的事情 promise 链。上面的代码不起作用,给我留下了 Uncaught (in promise) 错误。

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

最佳答案

这应该可以解决问题:

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 做的事情 - 很棒的技术!

关于javascript - Aurelia 中 fetch() 的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35520790/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com