[英]Javascript fetch api use custom error message
我正在尋找一種使用本機 javascript fetch api 處理錯誤的方法。 曾經使用 jQuery,但我正在嘗試使用更多的原生 javascript 功能。
我找到了這個博客並且喜歡這種方法: https://learnwithparam.com/blog/how-to-handle-fetch-errors/
fetch(url)
.then((response) => {
if (response.status >= 200 && response.status <= 299) {
return response.json();
}
throw Error(response.statusText);
})
.then((jsonResponse) => {
// do whatever you want with the JSON response
}).catch((error) => {
// Handle the error
console.log(error);
});
但是,在捕獲中,我得到了屬於 HTTP 代碼的 statusText。 對於 400 例如Bad request
。 但這不是我想要的,我對服務器的調用將准確地響應錯誤。 所以我想使用響應正文作為錯誤。 我嘗試了不同的方法,但如果 HTTP 代碼為 400,我無法獲得響應正文。對於 jQuery,我使用了response.responseJSON.html
。 但這不適用於 fetch api。
那么我怎樣才能將響應正文用作錯誤代碼。
fetch
API旨在與async
函數一起工作。 如果您可以使外部 function async
,您的代碼將變為:
try {
const response = await fetch(url);
if (!response.ok) {
const text = await response.text();
throw Error(text);
}
const jsonResponse = await response.json();
// do whatever you want with the JSON response
} catch (error) {
console.log(error);
}
否則,它會變得有點復雜:
fetch(url)
.then((response) => {
if (response.ok) {
return response.json();
}
return response.text().then((text) => throw Error(text));
})
.then((jsonResponse) => {
// do whatever you want with the JSON response
}).catch((error) => {
// Handle the error
console.log(error);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.