Javascript 当响应正文包含错误消息时,重试Array.forEach获取请求
我已经构建了一个基本的web应用程序,可以从本地数据库检索发票数据,并将数据发布到Wave Accounting 我发现api中的错误包含在响应体中 我正在试图找到一种解决方案,如果api的响应体包含错误,那么可以重试请求。(它始终返回200作为状态) 我尝试了在stackexchange上找到的其他解决方案(将限制参数传递给函数),并在获取请求失败时重试,直到达到限制数为止。 逻辑和数据都工作得很好-只是偶尔在api端出现内部服务器错误,我需要找到一种处理方法Javascript 当响应正文包含错误消息时,重试Array.forEach获取请求,javascript,foreach,graphql,fetch,Javascript,Foreach,Graphql,Fetch,我已经构建了一个基本的web应用程序,可以从本地数据库检索发票数据,并将数据发布到Wave Accounting 我发现api中的错误包含在响应体中 我正在试图找到一种解决方案,如果api的响应体包含错误,那么可以重试请求。(它始终返回200作为状态) 我尝试了在stackexchange上找到的其他解决方案(将限制参数传递给函数),并在获取请求失败时重试,直到达到限制数为止。 逻辑和数据都工作得很好-只是偶尔在api端出现内部服务器错误,我需要找到一种处理方法 function postInv
function postInvoicesToWave(data, limit = Number.MAX_VALUE) {
let query = `mutation ($input: InvoiceCreateInput!){invoiceCreate(input: $input){didSucceed inputErrors {code message path} invoice {id title invoiceNumber invoiceDate items {product {id name} description quantity price subtotal {value currency { symbol }} total { value currency { symbol } } taxes { amount { value } salesTax { id name} } } } } }`;
fetch('https://gql.waveapps.com/graphql/public', {
method: 'POST',
headers: {
'Authorization': 'Bearer <access token>',
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
query,
variables: {
input: {
"businessId": `${data.businessId}`,
"customerId": `${data.customerId}`,
"status": "SAVED",
"invoiceNumber": `${data.invoice}`,
"poNumber": `${data.po}`,
"invoiceDate": data.date,
"currency": "EUR",
"items": [
{
"description": `${data.description}`,
"quantity": 1,
"unitPrice": data.price,
"productId": `${data.productId}`,
"taxes": { "amount": 0, "salesTaxId": `${data.salesTaxId}`} //taxes normally get paid - this is just testing :)
}
]
}
}
})
}).then(r => r.json())
.then(res => {
if(res.hasOwnProperty("errors") && --limit){
console.log(limit); //console logs random numbers 6, 18, 5 for example on the last test
return postInvoicesToWave(data, limit);
}
else {
//update the database with posted success value
}
});
}
基本上,我试图实现的是将一个参数传递给array.forEach函数,如果api响应体包含错误,则使用此参数作为最大重试次数
请原谅我可能包含的问题措辞和任何语法错误-如果有任何建议,我将编辑问题
提前感谢。首先,在不知道错误是什么的情况下盲目地重试api调用似乎有些奇怪 但是将参数传递给
forEach
主体中的函数的最简单方法是:
const retries = 3;
data.forEach((data) => postInvoicesToWave(data, retries));
我目前正在处理测试数据。我没有得到任何错误的格式等!我收到的唯一错误是一个内部服务器错误,我打算在生产中处理其他错误。目前,我只是尝试在返回任何错误时重试获取请求:
const retries = 3;
data.forEach((data) => postInvoicesToWave(data, retries));