为什么我的JavaScript Fetch无法获取错误对象
我有一个JavaScript,可以对站点的后端进行fetchpost调用。如果post调用进行顺利,则Fetch能够处理响应。如果post调用中出现错误,则Fetch无法处理该错误 这是我的密码:为什么我的JavaScript Fetch无法获取错误对象,javascript,error-handling,fetch,Javascript,Error Handling,Fetch,我有一个JavaScript,可以对站点的后端进行fetchpost调用。如果post调用进行顺利,则Fetch能够处理响应。如果post调用中出现错误,则Fetch无法处理该错误 这是我的密码: async function startFetch(url, data_post){ return fetch(url, { method: 'POST', // or 'PUT' body: JSON.stringify(data_post), // data can be `
async function startFetch(url, data_post){
return fetch(url, {
method: 'POST', // or 'PUT'
body: JSON.stringify(data_post), // data can be `string` or {object}!
headers:{
'Content-Type': 'application/json'
}
})
.then(response => response.json());
}
async function makeFetch(arrRows){
let url = 'somebackendpost';
for(const item of ArrRows){
let data_post = {};
data.name = item;
await startFetch(url, data_post)
.then(data => {
//when the fetch is okay, this part is executed
console.log(data);
//do other things like output to html
$('#result').append('<p>' + data.result + '</p>');
})
.catch(error ={
//a timeout 504 error occured, but this part seemed not to execute
console.log('error is', error);
//the code below is wrong (but has since been removed then)
//Is this the reason why the catch error part did not work?
//Since the code below has been removed, can I expect the catch error to now work?
$('#result').append('<p>' + data.result + '</p>');
});
}
}
function startProcess(){
//called by button click
let arrRows = ["Row1", "Row2", "Row3"];
makeFetch(arrRows);
}
尝试更新
startFetch
方法,在尝试将响应解析为json之前,首先检查fetch响应是否为“ok”。在您尝试解析json之前,这将捕获大多数错误场景(当前未被检测到)
因此,以下更新应允许您正确响应错误:
async function startFetch(url, data_post){
return fetch(url, {
method: 'POST', // or 'PUT'
body: JSON.stringify(data_post), // data can be `string` or {object}!
headers:{
'Content-Type': 'application/json'
}
})
.then(response => {
// Check that the response is valid and reject an error
// response to prevent subsequent attempt to parse json
if(!response.ok) {
return Promise.reject('Response not ok with status ' + response.status);
}
return response;
})
.then(response => response.json());
}
希望这有帮助 @JaimeDolorjr。不客气,如果你还需要帮助,请告诉我:)我有点进步。拒绝现在读取return-Promise.reject('Response not ok with status'+Response.status));这就像一个符咒:-)
async function startFetch(url, data_post){
return fetch(url, {
method: 'POST', // or 'PUT'
body: JSON.stringify(data_post), // data can be `string` or {object}!
headers:{
'Content-Type': 'application/json'
}
})
.then(response => {
// Check that the response is valid and reject an error
// response to prevent subsequent attempt to parse json
if(!response.ok) {
return Promise.reject('Response not ok with status ' + response.status);
}
return response;
})
.then(response => response.json());
}