This connect expected to error but I should able to caught promise rejections. But the results that I get said unhandled promise rejection. ( I got double mongoError from console.log() as expected ) Thank you for your suggestion and advice.
mongodbModule.js file
var connection;
module.exports.mongodbConnect = () => {
return new Promise(async (resolve, reject) => {
if (!connection) {
try {
connection = await mongoClient.connect(uri, opts);
let database = connection.db(dbName);
resolve(database)
} catch (mongoErr) {
console.log(mongoErr);
reject(mongoErr);
}
}
});
};
app.js
const mongoConnect = require('./modules/mongodbModule').mongodbConnect;
const connectDb = () => {
return new Promise( async (resolve,reject) => {
try {
let db = await mongoConnect()
resolve(db);
} catch (err) {
reject(err);
}
});
};
connectDb()
.then((db) => {
console.log(db)
})
.catch((mongoErr) => {
console.log(mongoErr)
throw mongoErr;
});
error
(node:26864) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
(node:26864) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
You should not throw the error inside the catch.
.catch(e => {
console.log(e);
process.exit(1); // to exit with no error use 0
});
A thrown error in Express.js will shut down your application.
Related
(node:13384) UnhandledPromiseRejectionWarning: TypeError: cb is not a function
I am using passport js for authentication for my website, I am able to get all routes but when I try to sign up that is post router so in the console I am seeing these err, my data saved in DB but after posting my page loading continuously.
here these err what I am getting
(node:13384) UnhandledPromiseRejectionWarning: TypeError: cb is not a function
at C:\Users\SBCS\Desktop\AppBlog\node_modules\passport-local-mongoose\index.js:247:59
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use node --trace-warnings ... to show where the warning was created)
(node:13384) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:13384) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
and here is my post router code
app.post("/sign-up",(req,res)=>{
const username = req.body.username
const email = req.body.email
const password = req.body.password
User.register( {username:username}, req.body.email,req.body.password ,(err,user)=>{
if(err){
console.log(err);
res.redirect("/sign-up")
}else{
passport.authenticate("local" )(req,res, function (){
res.redirect('/compose')
})
}
})
and here is my mongoose connection
mongoose.connect('mongodb://localhost:27017/blog', {useNewUrlParser: true, useUnifiedTopology: true,useFindAndModify: false}).catch(err => console.log(err))
mongoose.set('useCreateIndex',true);
thanks
when I am getting err node js referring me this modules code see here
schema.statics.register = function(user, password, cb) {
// Create an instance of this in case user isn't already an instance
if (!(user instanceof this)) {
user = new this(user);
}
const promise = Promise.resolve()
.then(() => {
if (!user.get(options.usernameField)) {
throw new errors.MissingUsernameError(options.errorMessages.MissingUsernameError);
}
})
.then(() => this.findByUsername(user.get(options.usernameField)))
.then(existingUser => {
if (existingUser) {
throw new errors.UserExistsError(options.errorMessages.UserExistsError);
}
})
.then(() => user.setPassword(password))
.then(() => user.save());
if (!cb) {
return promise;
}
promise.then(result => cb(null, result)).catch(err => cb(err));
};
this is passport-local-mongoose module code
i got answer
this cause by
User.register( {username:username}, req.body.email,req.body.password ,(err,user)=>{
if(err){
line of code and after spending more time on it,I got some solution
solution is here
User.register({username: req.body.username}, req.body.password, function(err, user){
also if you want to send user name you can send it like this
User.register({username: req.body.username,name: req.body.registerName}, req.body.password, function(err, user){
thanks .....
const Car = mongoose.model('Car', new mongoose.Schema({
name: {
type: String,
required: true,
}
}));
router.put('/:id', async (req, res) => {
const { error } = joiValidator(req.body);
if (error) return res.status(400).send(error.details[0].message)
try {
const car= await Car.findByIdAndUpdate(req.params.id, { name: req.body.name }, {new: true })
} catch (error) {
return res.status(404).send('not found.');
}
res.send(car);
})
i am successfully connected to mongoDB using mongoose, its only when i try to mock an error by giving a wrong id as an input i get the following error, even though i handled async and await with the trycatch block
(node:19392) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:19392) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
This is mainly because you are using try an catch after an if. In javascript the way of reading code is asynchronous so, if and try are executed at the same time. Also, you don´t need to use an async function here, as you are only calling one promise.
Here I let you a simpler code without async.
router.put("/:id", (req, res) => {
const { error } = joiValidator(req.body);
if (error) {
return res.status(400).send(error.details[0].message);
} else {
Car.findByIdAndUpdate(req.params.id,{ name: req.body.name },{ new: true },(err, car) => {
if (err) return res.status(404).send({ message: 'Not found', err });
return res.status(200).send(car);
}
);
}
});
I am trying to run an async CMD command on with my Node server. Unfortunately my functions always throws an UnhandledPromiseRejectionWarning. I searched for results but never found a solution that fits my code.
(node:20704) UnhandledPromiseRejectionWarning: 0
(node:20704) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:20704) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I know that the error states I should use a catch block but I really dont know how I should implement that with the lambda implementation I used.
const exec = require('child_process');
const execWindowsCommand = new Promise(async (resolve, reject) => {
const process = exec.spawn('cmd', [ '/c', 'dir' ]);
process.on('data', data => resolve(data));
process.on('error', err => reject(err));
process.on('close', err => reject(err));
process.on('unhandledRejection', function(reason, promise) {console.log(promise);});
});
app.get("/cmdWIN", async(req, res) => {
execWindowsCommand()
.then(function(value) {
console.log(value);
res.send(value);
})
.catch((error) => {
console.error(error);
res.send(error);
});
});
const sendData = (response, language, locale) => {
try {
console.log(response.reduce((prev, curr) => prev + curr.confirmed, 0));
} catch (error) {
console.error('error');
}
};
and my fetch function:
const fetchGeneralData = async (param) => {
try {
let res = await axios.get(
`https://localhost/api/${param}`,
);
msg.reply(sendData(res.data.results), language, momentLocale);
} catch (error) {
msg.reply(language.errorMessage);
console.error(error, 'Error on fetchGeneralData');
}
};
The console.log shows me the correct value but for some reason, I still getting the errors.
I have tried adding async/await inside sendData but it did not work. My fetchGeneralData func works fine when i'm trying to return the date without modify it.
Here is the full message:
(node:5500) UnhandledPromiseRejectionWarning: Error: Evaluation failed: TypeError: t.match is not a function
(node:5500) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:5500) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I have a service that analyses websites, compresses their sources like CSS Documents, Images etc. I have 2 functions, one is Socket.IO socket.on() method with async callback function. Another is main function for service.
socket.on('run', async options => {
debug(`${options.target} Adresine Bir Kullanıcı İstek Yaptı!`);
let user = null;
console.log(options);
if(options.token) {
user = await User.findById(jwt.verify(options.token, config.get('jwtPrivateKey'))._id);
options.userId = user._id.toString();
} else if(options.visitor) {
user = await Visitor.findById(options.visitor._id);
if(user.report) {
return socket.emit('error', new Error('You have exceeded your report limit'));
} else {
options.userId = user._id.toString();
}
}
if(options.userId) {
let userType = await UserType.find({ name: user.type });
if(userType.length > 0 && ((user.type == 'Visitor' && user.report == undefined) || (user.reports.length < userType[0].rights.reportsLimit.limit || userType[0].rights.reportsLimit.unlimited))) {
options.rights = userType[0].rights;
let { error, data } = await wrapper(runService(options.target, options, socket));
if(error) {
console.log('Here', error);
return socket.emit('error', error);
}
.
.
.
}
.
.
.
}
});
In the above function,
let { error, data } = await wrapper(runService(options.target, options, socket));
if(error) {
console.log('Here', error);
return socket.emit('error', error);
}
This part is important, because I call my main async service function runService with my async function wrapper function that is named wrapper. The wrapper function is this;
const wrapper = promise => (
promise
.then(data => ({ data, error: null }))
.catch(error => ({ error, data: null }))
);
In my main async service function, I only throw an error;
async function runService(target, options, socket) {
throw new Error('any error');
}
But the expected output is much different from actual output. Here is the output of this code;
Here Error: any error
at startService (C:\Projeler\OpDetect\Background-Service\lib\app.js:404:11)
at Socket.socket.on (C:\Projeler\OpDetect\Background-Service\app.js:73:57)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:16600) UnhandledPromiseRejectionWarning: Error: any error
at startService (C:\Projeler\OpDetect\Background-Service\lib\app.js:404:11)
at Socket.socket.on (C:\Projeler\OpDetect\Background-Service\app.js:73:57)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:16600) UnhandledPromiseRejectionWarning: Unhandled promise rejection.
This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:16600) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate
the Node.js process with a non-zero exit code.
My expectation about the output is, like this;
Here Error: any error
at startService (C:\Projeler\OpDetect\Background-Service\lib\app.js:404:11)
at Socket.socket.on (C:\Projeler\OpDetect\Background-Service\app.js:73:57)
at process._tickCallback (internal/process/next_tick.js:68:7)
Because I already handled the promise rejection with my wrapper function and catched the rejection, Why is 2 more UnhandledPromiseRejectionWarning errors on rejection?
Also, the line,
return socket.emit('error', error);
is not calling for no reason. It should have been called when the if statement truthy. Why is not this socket.emit function called?
As best practice use try {} catch(){} with async/await.
For ex.
userUtils.signUp = async (userName) => {
try {
const callFunction = await userUtils.checkExistancy(userName);
if (!callFunction.isExist) {
...
} else {
...
}
} catch (err) {
console.log(err);
throw err;
}
};
in your case it will be like
socket.on('run', async options => {
try {
user = await User.findById(jwt.verify(options.token, config.get('jwtPrivateKey'))._id);
options.userId = user._id.toString();
return true;
} catch (err) {
throw err;
}});