I'm trying to implement try/catch on javascript with Fetch API using PATCH Method. Most of the time when the fetch success I get a 400 (Bad Request) error and I don't know why, I wonder If I'm forgetting to add an if statement inside the try statement to check the response status before jumping into the catch statement. I also created a function called retry() to not allow the user to make more than 3 failing calls. And if I make it fail I am not able to see the numberOfRetries log updated.
const retry = async (callback, numberOfRetries) =>
await callback(numberOfRetries)
export const updateValue = async (name, active, numberOfRetries = 0) => {
try {
await fetch(`${apiUrl}/device/${name}?active=${active}`, {
method: 'PATCH',
headers: {
Accept: 'application/json',
'Content-type': 'application/json; charset=UTF-8'
},
body: JSON.stringify({
name,
active
})
})
console.log('ok')
} catch (error) {
if (numberOfRetries >= 2) {
return
}
console.log(`retry number ${numberOfRetries}`)
return await retry(updateValue, ++numberOfRetries)
}
}