noting is working in catch block in node js - javascript

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
Edit
the above code is simple example of my problem the actual code is following
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 (err) {
console.log(err);
}
});
i am facing issue with the algoTrade function, inside this function i am calling some apis with axios

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

Should I write all my route handling code in a try-catch block?

Is this good use of try…catch, or should I write everything in try block? I am trying to prevent nested try…catch blocks.
router.post('/refresh', async (req, res) => {
const refreshToken = req.body.token;
let decoded;
try {
decoded = jwt.verify(
refreshToken,
process.env.REFRESH_TOKEN_SECRET,
);
} catch(error) {
return res.sendStatus(401);
}
// … use decoded variable here
});
You'll never need to nest try/catches - a catch() will catch all errors underneath it.
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch
Specifically:
The try...catch statement marks a block of statements to try and specifies a response should an exception be thrown.
However if you're unsure that refreshToken will exist (it's a good example not to trust web browsers), you can add it to the block you're catching errors in:
router.post('/refresh', async (req, res) => {
let decoded;
try {
const refreshToken = req?.body?.token;
if ( ! token ) {
throw new Error('Token not supplied!')
}
decoded = jwt.verify(
refreshToken,
process.env.REFRESH_TOKEN_SECRET,
);
} catch(error) {
return res.sendStatus(401);
}
// … use decoded variable here
});

Please help me solve JavaScript Asyncronus issue

I have code in connect.js like this
const sqlite3 = require('sqlite3').verbose();
class Connection {
static connect() {
let db = new sqlite3.Database('../SQlite-tester-001/db/sqlite_tester001.db', sqlite3.OPEN_READWRITE, (err) => {
if (err) {
console.error(err.message);
}
else {
console.log('Connected to the tester database.');
}
});
return db
}
}
module.exports = Connection;
And I try to call it from insert.js like this
const Connection = require('./connect');
(async () => {
let db = await Connection.connect();
await console.log('This line is below Connection.connect()');
})();
console.log('This line is below Async function');
However, the result is not what I wanted like below
wittinunt#Wittinunt-VCIS-PC:~/GitHub/SQlite-tester-001$ node insert.js
This line is below Async function
This line is below Connection.connect()
Connected to the tester database.
What I expected it is should be like
Connected to the tester database.
This line is below Connection.connect()
This line is below Async function
I'm very new to JavaScript and now I very confuse about 'async-await'.
Please help.
There are callback/Promise/asny,await ways to handle asynchronous
And in the above code, callback and async/await are used in duplicate among the asynchronous handling methods.
The callback function works.
So delete the callback function and run.
[However, the function must support Promise]
const sqlite3 = require('sqlite3').verbose();
class Connection {
static async connect() {
try {
let db = await new sqlite3.Database('../SQlite-tester-001/db/sqlite_tester001.db', sqlite3.OPEN_READWRITE);
console.log('Connected to the tester database.');
} catch (err) {
console.error(err.message);
}
}
}
module.exports = Connection;
if error occrued, then "catch block" catch error.

Browser tab keeps loading after express js get method

I'm trying to build a simple REST API using Express.js, first time using it.
So I run the Express application generator using npx express-generator. Then, on /routes/users.js, I add a get method to retrieve data from an MSSQL database with the following code:
router.get('/api/v1/test', (req, res) => {
(async () => {
try {
let pool = await sql.connect(dbConfig);
let result1 = await pool.request().query('select * from andromedadb.dbo.test');
console.dir(result1);
} catch (err) {
console.log('err', err);
}
})();
});
I know the connection is successful because the console prints the following:
{
recordsets: [ [ [Object] ] ],
recordset: [ { id: 1, name: 'hello', age: 17 } ],
output: {},
rowsAffected: [ 1 ]
}
My issue is that the browser tab keeps loading and executing the get method over and over.
I also tried the code snippet on https://www.js-tutorials.com/nodejs-tutorial/simple-example-of-nodejs-express-with-mssql/#Listing_Nodejs_MSSQL_Using_Express, but the very same thing was happening.
Thanks in advance.
You need to send the response back to the request. I just modified your code, Look at the changes in the below code.
router.get('/api/v1/test', (req, res) => {
(async () => {
try {
let pool = await sql.connect(dbConfig);
let result1 = await pool.request().query('select * from andromedadb.dbo.test');
console.dir(result1);
res.status(200).send(result1);
} catch (err) {
res.status(401).send(err);
console.log('err', err);
}
})();
});
You need to send back some response with your res object or call the next() function to go into your next middleware, otherwise you are just leaving your request hanging, thus the infinite load. Add a res.send() or res.json() function to mark the end of your function.
router.get('/api/v1/test', (req, res) => {
(async () => {
try {
let pool = await sql.connect(dbConfig);
let result1 = await pool.request().query('select * from andromedadb.dbo.test');
console.dir(result1);
res.status(200).send("Received the response successfully");
} catch (err) {
console.log('err', err);
res.status(500).send("Something went wrong");
}
})();
});
How are you calling the route from the front end application?
As you are using an async function for your get method, remember to use 'await':
const response = await getRecordSet();
// do stuff with 'response'

Catching errors within async await

I have the following function:
exports.signup = async(req, res) => {
console.log('signup');
const user = new User({
username: req.body.username,
email: req.body.email,
password: bcrypt.hashSync(req.body.password, 8)
});
try {
if (await user.save()) {
if (isNonEmptyArray(req.body.roles)) {
// How do I catch this error? can be a role error or db error
const roles = await Role.find({name: { $in: req.body.roles }}).exec()
user.roles = roles.map(role => role._id);
if (await user.save()) {
success(res, 'Registered!');
}
} else {
// How do I catch this error? can be a role error or a db error
const role = await Role.findOne({name: 'user'}).exec();
user.roles = [role._id];
if (await user.save()) {
success(res, 'Registered!');
}
}
}
} catch(error) {
fail(res, {message: 'Database internal error occured.'});
}
};
Is it correct that the catch will trigger for all errors in the block including calls to await Role.find({name: { $in: req.body.roles }}).exec()? How would I catch this error independently? Do I need to add a try and catch within the try and catch statement?
like you said you can use another try-catch block to distinguish which error are you catching.
try {
const role = await Role.findOne({name: 'user'}).exec();
} catch(err) {
console.log(err);
}
Another idea might be to use the promises and catch the error in each .catch segment, for example
var query = Role.findOne({name: 'user'});
query.exec().then(function () {
// handle success
}).catch(function (err) {
// handle error
});
anyway there are some important to feature to keep in mind when using async/await and try-catch block, I'll put here the conclusion of an article and the link to it if you are interested:
conclusion:
We can use try...catch for synchronous code.
We can use try...catch (in combination with async functions) and the .catch() approaches to handle errors for asynchronous code.
When returning a promise within a try block, make sure to await it if you want the try...catch block to catch the error.
Be aware when wrapping errors and rethrowing, that you lose the stack trace with the origin of the error.
font: https://itnext.io/error-handling-with-async-await-in-js-26c3f20bc06a

Synchronous and asynchronous vs callback in mongoose

hi guys i am new in node and have this simple question , what is difference between this two sniped
Note: i know async / await functionality and also in front-end application it is best practice for handle async action but in node in working with mongoose i want know which approach better for handle
first solution
// for example we pass this function as controller to route handler
exports.myController = async (req, res, next) => {
try {
const data = await Model.find();
const some = await new Model(data).save();
} catch(e) {
next(e);
}
}
second solution
exports.myController = (req, res, next) => {
const data = Model.find((err, data_) => {
const some = new Model(data_);
some.save((err, result) => {
....
})
});
}
i want to know when i have an error from mongoose , in second way can throw error like this
// in callback function
if (err) {
throw Error();
}
but how can i handle this in async/await solution
you simply throw it or log it in your catch block:
try {
const data = await Model.find();
const some = await new Model(data).save();
} catch(e) {
throw e;
next(e);
}
the async/await is working like promises but without no nesting callbacks and it throws an error synchronous to what errors first and stop from executing the other lines.
Based in your edited Note:
you should always go for the async solution way in nodejs or even for anything related to javascript it's the best composable and reusable solution.

Categories