我正在寻找一种使用本机 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);
});
Run Code Online (Sandbox Code Playgroud)
然而,在 catch 中我得到了属于 HTTP 代码的 statusText。以400为例Bad request。但这不是我想要的,我对服务器的调用将准确地响应错误。所以我想使用响应正文作为错误。我尝试了不同的方法,但如果 HTTP 代码为 400,我无法获取响应正文。对于 jQuery,我使用了response.responseJSON.html. 但这不适用于 fetch api。
那么我怎样才能使用响应正文作为错误代码。
该fetchAPI旨在与async函数完美配合。如果你可以创建你的外部函数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);
}
Run Code Online (Sandbox Code Playgroud)
否则,事情会变得更复杂:
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);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6732 次 |
| 最近记录: |