Home > Enterprise >  noting is working in catch block in node js
noting is working in catch block in node js

Time:01-12

i have a simple express server in which i have function, in this function i try to access data from mongoDB , here is the code

const  test =async()=>{
try{
    const data = await User.findOne({_id: "1234"})
}catch(err){
    const data = await User.findOne({_id: "4567"})
}

in this function, try block is working fine but whenever error occurs code inside catch block is not working, i have try return and console.log() in catch block which is also not working, here is code

catch(err){
   console.log("hello")
}

or

catch(err){
   return "hello"
}

nothing is not working in catch block, i cant understand this problem please help me

CodePudding user response:

The problem in your code is that you are re-declaring the data variable inside the catch block, which means that the original variable declared in the try block is no longer in scope. This is why the return statement or console.log() is not working.

You can fix this by either returning the value from the catch block or simply move the variable declaration outside of the try-catch block, like this:

const test = async() => {
let data;
try {
    data = await User.findOne({_id: "1234"});
} catch(err) {
    data = await User.findOne({_id: "4567"});
}
console.log(data);
return data;

}

Or

const test = async() => {
try {
    const data = await User.findOne({_id: "1234"});
    return data;
} catch(err) {
    console.log("hello")
}

}

In this way, you will be able to access the data variable inside the catch block and do what ever you like to do with it, whether it is returning it, or logging the data to console.

CodePudding user response:

I see the issue with your code in comments. The issue is that catch block is not implemented to catch error thrown by try block hence the code terminates use it like this

router.post("/", async (req, res) => {
    const data = req.body;
    data.time = new Date();
    data._id = uniqid();
    data.orderStatus = "Pending";
    const tradeData = await TradePara.create(data);
    try {
        algoTrade(data);
    } catch(e) {
        console.log("not working", e);
    }
});

instead of using catch{}, implement catch block.

  • Related