Node JS spawn child_process throws UnhandledPromiseRejectionWarning - javascript

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);
});
});

Related

UnhandledPromiseRejectionWarning: TypeError: user.destroy is not a function (NodeJS- Sequelize)

I'm following a tutorial on NodeJs on youtube, but when it comes to deleting users by id, it doesn't work like what's on the tutorial. But on that video everything seems to work perfectly. This is my code. Where am I wrong? Looking forward to everyone's comments.
let deleteUserByID = (userId)=>{
return new Promise(async(resolve, reject)=>{
try{
let user = await db.User.findOne({
where: {id: userId}
})
if(user){
await user.destroy();
}
resolve();
}catch(e){
reject(e);
}
})
}
And this is the error displayed on the terminal screen:
(node:11140) UnhandledPromiseRejectionWarning: TypeError: user.destroy is not a function
at...
at...
at...
...
(Use `node --trace-warnings ...` to show where the warning was created)
(node:11140) 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:11140) [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.
After a while of searching on the internet, i found the solution, everything is working and seems to be fine, anyone can refer to it if they have the same error as mine.
Upvote if it works for you
let deleteUserByID=(userId)=> {
return db.User.destroy({ where: { id: userId } })
.then(rows => Promise.resolve(rows === 1))
}
Or another solution:
let deleteUserByID = (userId) => {
return new Promise(async (resolve, reject) => {
await db.User.findOne({
where: {
id: userId
}
})
await db.User.destroy({
where: {
id: userId
}
})
resolve({
errCode: 0,
message: `The user is deleted`
})
})
}

Unhandled promise rejection nodejs

I am trying to use openweather-apis to connect to a dialogflow agent. I am new to promises and I keep getting the warning UnhandledPromiseRejectionWarning and I'm not sure on how to fix this.
Currently I have 2 files weather.js, which makes the api call
const api = require("openweather-apis")
api.setAPPID(process.env.API_KEY)
api.setUnits("metric")
module.exports = {
setCity: function(city) {
api.setCity(city)
},
getWeather: function() {
return new Promise(function(resolve, reject) {
api.getTemperature(function(err, temp) {
if (err) reject(err)
resolve(temp)
})
})
}
}
And I make use of weatherinCity.js, which retrieves the city from the agent, calls the calling function and then sends a response to the user.
const weather = require("../../weather")
module.exports = {
fulfillment: function(agent) {
const city = agent.parameters.geo_city
weather.setCity(city)
weather.getWeather().then(function(temp) {
agent.add(
"It is ${temp} degrees Celcius in ${city}"
)
}).catch(() => {
console.error("Something went wrong")
})
}
}
full error message:
(node:2896) UnhandledPromiseRejectionWarning: Error: No responses defined for platform: DIALOGFLOW_CONSOLE
at V2Agent.sendResponses_ (C:\Users\Coen\Desktop\ciphix-ca-case\node_modules\dialogflow-fulfillment\src\v2-agent.js:243:13)
at WebhookClient.send_ (C:\Users\Coen\Desktop\ciphix-ca-case\node_modules\dialogflow-fulfillment\src\dialogflow-fulfillment.js:505:17)
at C:\Users\Coen\Desktop\ciphix-ca-case\node_modules\dialogflow-fulfillment\src\dialogflow-fulfillment.js:316:38
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:2896) 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:2896) [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 error indeed happened because this code fails to handle the Promise Rejection. While I'm not sure which Promise Rejection that failed to handle, but based on this and this GitHub discussions. It seems you need to return the agent.add() function.
I recommend trying async-await style with the consequence that you have to add a try catch block
module.exports = {
fulfillment: async function(agent) {
try {
const city = agent.parameters.geo_city
weather.setCity(city)
let temp = await weather.getWeather()
agent.add(
"It is ${temp} degrees Celcius in ${city}"
)
} catch (err) {
console.error("Something went wrong")
console.error(err)
}
}
}
Every error that is thrown on the try block should be caught in a catch block. Don't forget to add async before the function.
it will not solve your problem but generally speaking, i would add "return" after if(err). because otherwise the call to resolve would be done. in your particular case it will do no harm, as because of the nature of promises it will be ignored. but if you had written anything between reject and resolve it would have been executed.
// best practice
if (err) return reject(err)
for your problem, i've just tried this fast test to convice myself that even throws are catched by .catch() so i think you must be running a bad/old nodejs version, or the code you provided is not complete, and the failure is elsewere. I dont see any line pointing to your own code in the log O_o (only node_modules).
which nodejs version is it ?
var p = new Promise((resolve, reject) => {
throw new Error('test');
resolve('ok')
})
p.then(console.log).catch(function(err) {
console.error('err', err)
});

UnhandledPromiseRejectionWarning when using .reduce

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.

Error: Uncaught (in promise): Unhandled promise rejections

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.

UnhandledPromiseRejectionWarning after catching a rejected promise

Running the following code with Node v8.1.4:
testPromise((err) => {
if (err) throw err;
});
function testPromise(callback) {
Promise.reject(new Error('error!'))
.catch((err) => {
console.log('caught');
callback(err);
});
}
returns the following:
caught
(node:72361) UnhandledPromiseRejectionWarning: Unhandled promise rejection
(rejection id: 2): Error: test
(node:72361) [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 would have expected an uncaughtException to be thrown?
How can I turn this into an uncaught exception?
You are essentially throwing inside the catch callback. This is caught and turned into another rejected promise. So you'll get no uncaughtException
Promise.reject("err")
.catch(err => {
throw("whoops") //<-- this is caught
})
.catch(err => console.log(err)) // and delivered here -- prints "whoops"
One thing to be careful of is asynchronous function that throw. For example this IS an uncaught exception:
Promise.reject("err")
.catch(err => {
setTimeout(() => {
throw("whoops") // <-- really throws this tim
}, 500)
})
.catch(err => console.log(err)) //<-- never gets caught.

Categories

Resources