[英]Error handling for fetch() in Aurelia
我有一個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
回去只是一個簡單的錯誤信息給調用視圖。 我可以成功調用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
做的Promise.race
- 很棒的技巧!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.