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
- 很棒的技巧!
归档时间: |
|
查看次数: |
5246 次 |
最近记录: |