Aurelia中fetch()的错误处理 [英] Error handling for fetch() in Aurelia
问题描述
我有一个API,其中包含服务器引发错误时出错的有用描述(状态= 500)。该描述作为响应文本的一部分。我的客户端代码,使用Aurelia,使用通用方法通过 aurelia-fetch-client
调用api来进行调用:
I have an API that includes a useful description of what went wrong when an error is raised by the server (status = 500). The description comes as part of the response text. My client code, using Aurelia, calls the api via aurelia-fetch-client
using a generic method to make the call:
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()');
}
});
}
请注意,我想捕获服务器(获取或超时)错误一致的方式,然后抛出
只返回一个简单的错误消息给调用视图。我可以成功调用 callRemoteService
,在返回500时捕获错误:
Note that I want to catch the server (fetch or timeout) errors in a consistent way, and then throw
back just a simple error message to the calling view. I can invoke callRemoteService
successfully, catching errors when a 500 is returned with:
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
提供 text()
方法,该方法返回一个promise,这会干扰我非常开心的promise链接。上面的代码不起作用,给我留下了 Uncaught(承诺)
错误。
However, I'm having trouble accessing the response text, because the fetch
provides the text()
method that returns a promise, and that's interfering with my otherwise happy promise chaining. The code above doesn't work, leaving me with an Uncaught (in promise)
error.
希望有一个访问该响应文本的好方法?
Hopefully there's a good way to access that response text?
推荐答案
这应该可以解决问题:
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)
]);
}
顺便说一句,我喜欢你用<$ c $做的事情c> Promise.race - 很棒的技巧!
by the way, I like what you're doing with Promise.race
- nice technique!
这篇关于Aurelia中fetch()的错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!