私は、サーバによってエラーが発生したときに何が問題になったのかを示す有用な説明を含むAPIを持っています(ステータス= 500)。説明は応答テキストの一部として提供されます。一貫した方法でエラーを(フェッチまたはタイムアウト)Aureliaのfetch()のエラー処理
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
:オーレリアを使用して私のクライアントコードは、呼び出しを行うために、一般的な方法を使用してaurelia-fetch-client
経由でAPIを呼び出します呼び出し側のビューに単純なエラーメッセージを返します。私は500がで返されたときにエラーをキャッチし、成功しcallRemoteService
を呼び出すことができます。
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()
方法を提供するので、私は、応答テキストへのアクセスのトラブルを抱えている、それはとの干渉です私のそうでなければ幸せな約束の連鎖。上記のコードはうまくいきません。私には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
でやっていることが好き - すてきな技術を:
'(最初のコードの)'の前に 'catch'を置いていますか? – dandavis
@dandavis私は運がなければいくつかのバリエーションを試しました。しかし、レースの中で約束を守るというジェレミーの提案はうまくいくようだ。 –