need help with error handling in async functions in js

So i fetch some details from backend and get in frontend..so if i turn off my internet it shows error as "cannot read properties undefined" , so i add as if(!res) throw error and provide catch block in frontend but it shows error instead it catch and store on error variable heres the code: react code
async function fetchdata(){
try{
let res = await axios.get(`http://localhost:4040/delivery/food/${foodName}`)
if(!res || !res.data ){
throw new Error('Network response was not ok')
}

setFoodData(res.data)
}catch (err) {

let errMsg = "Something error occur"
if(err.response.data){
errMsg = err.response.data
}
else if(err.message){
errMsg = err.message;
}
setError(errMsg);
console.log(err)

} finally {
setLoading(false);
}
}
fetchdata()
async function fetchdata(){
try{
let res = await axios.get(`http://localhost:4040/delivery/food/${foodName}`)
if(!res || !res.data ){
throw new Error('Network response was not ok')
}

setFoodData(res.data)
}catch (err) {

let errMsg = "Something error occur"
if(err.response.data){
errMsg = err.response.data
}
else if(err.message){
errMsg = err.message;
}
setError(errMsg);
console.log(err)

} finally {
setLoading(false);
}
}
fetchdata()
express.js
routes.get('/delivery/food/:foodName', async(req, res) => {
const foodName = req.params.foodName.toLocaleLowerCase();
try {
const FoodNameDb = await FoodDetailsModel.find({
Foodname: foodName
})
if (FoodNameDb) {
return res.status(200).json(FoodNameDb);
} else {
return res.status(400).send("Food not available for now")
}
} catch (e) {
console.log(e)
}
})
routes.get('/delivery/food/:foodName', async(req, res) => {
const foodName = req.params.foodName.toLocaleLowerCase();
try {
const FoodNameDb = await FoodDetailsModel.find({
Foodname: foodName
})
if (FoodNameDb) {
return res.status(200).json(FoodNameDb);
} else {
return res.status(400).send("Food not available for now")
}
} catch (e) {
console.log(e)
}
})
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server