Error "Unhandled promise rejection" with mysql query - javascript

I am trying to make a new data entry in BD with mysql from a page. But when throw me an error about promises
var mysql = require('mysql'); //Llamadi a MySql
var valida= require('./modulos/validaciones');
var conection = mysql.createConnection({
host: 'localhost', //Host
user: 'eleazarsb', //Usuario
password: 'eleazar616', //Contraseña
database: 'mydb' //Base de datos
}).connect(function(error) {
if (error) console.log('Problemas de conexion con mysql');
console.log("conexion Exitosa!");
});
var validaciones = {
user: false,
mail: false,
ced: false
}
//Pendiente: 02
valida.user(data).then((rows) => {
validaciones.user = rows;
})
valida.mail(data).then((rows) => {
validaciones.mail = rows;
})
valida.ced(data).then((rows) => {
validaciones.ced = rows;
registrar(validaciones);
})
function registrar(validaciones) {
if (validaciones.user == false && validaciones.mail == false && validaciones.ced == false) {
var query = conection.query(data.sqlquery(), (error, columna, campos) => {
if (error) throw error;
console.log("Entra en registro de BD");
console.log(columna);
});
}
else {
console.log("No se registro nada");
};
return query;
};
When 'conection.query(data.sqlquery()...' is execute the console throw me this error
(node:1588) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'query' of undefined
(node:1588) [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.
So, i cant see where is the error if conection.query( is declared in the beginning with conection=mysql.createConnection
I am new programming with NodeJs so i i accept any comment or suggestion of good programming practices
valida return a promise declared in another file
exports.mail= (data)=>{
return new Promise ((resolve,reject)=>{
var query=conection.query(data.valida_mail(),(error,rows)=>{
if (error) return reject (error);
if(rows[0]){
console.log("Email Invalido!");
resolve(true);
} else {
console.log("Email Valido");
resolve(false);
}
});
})
};
... for example

Will's explained why your code is failing. The reason you're seeing it as an "Unhandled rejection" error is that you're not handling your promises correctly.
One of the rules of promises is that you either pass on the promise chain to the level above you, or you handle errors. This code does neither (nor do others written largely the same way):
valida.user(data).then((rows) => {
validaciones.user = rows;
})
What if the promise returned by valida.user(data) rejects? Answer: Nothing handles it.
You must either hand off the promise then creates to something else, or handle rejections. (If you hand it off, the thing you had it off to has to hand it off again, or handle errors.)
To make that code handle errors, add a catch handler:
valida.user(data).then((rows) => {
validaciones.user = rows;
}).catch(err => {
// Do something with the error here
});

The error message is a bit misleading here. The important part is TypeError: Cannot read property 'query' of undefined which is referring to conection being undefined when it is called in registrar when that is called in the promise handler attached to valida.ced.
The issue is with the code:
var conection = mysql.createConnection({
...
}).connect(function(error) {
...
});
which is assigning the return value of the call to Connection.connect to your conection variable. Connection.connection does not return a value (source), so later when that promise resolves and tries to execute registrar(), conection is still and forever undefined, so there's no such thing as conection.query to be called. Try:
var conection = mysql.createConnection({
...
});
conection.connect(function(error) {
...
});
As T.J. points out, the other important part of the error message is that you should provide code to handle rejected promises. Use the catch function to attach these handlers.

Adding to the answers .
You are using node.js promises . So to handle all type of 'Unhandled promise rejection'. use this code at the main node.js app file
process.on('unhandledRejection', error => {
// Will print "unhandledRejection err is not defined"
console.log('unhandledRejection', error);
});
In case you missed catching some promise this will handle all of them.
Process
Node.js process is global , it contains unhandledRejection event for handling unhandled promise rejection .

Related

Async/await call returns undefined when used in conjunction with promises

I am having an issue where an Async call to my database returns undefined.
The function "findOne" retrieves one row from the database, but the .then(... function is executing before the row is returned.
I've tried changing what I return in the DB function findOne as well as adding an 'await' on the function call. I've also tried using Promise.resolve(db.findOne({requestbody}).then(... but no luck with that either.
Here is the db.findOne method
const findOne = async (req) => {
const { teamId, channelId, isClosed } = req;
return db.query('SELECT * FROM polls where team_id= $1 and channel_id =$2 and is_closed = $3 LIMIT 1',
[teamId, channelId, isClosed],
(error, results) => {
if (error) {
throw error;
}
console.log("\nDBRes: \n", results.rows[0])
return results.rows[0];
}
);
};
And here is where I call the function
app.post('/', (req, res) => {
const slashCommand = req.body.command;
switch (slashCommand) {
//...
//... Some other code
//...
case 'results':
db.findOne({
teamId: requestBody.team_id,
channelId: requestBody.channel_id,
isClosed: false,
})
.then((row) => {
console.log(row);
const poll = pollFuncs.getPollfromResultRow(row);
const displayText = pollFuncs.getFormattedPollResults(poll);
res.status(200).send({
text: displayText,
});
});
break;
//... The rest of the function
Here are the logs I am getting.
Note* I am currently logging the "row" object both inside the .then(...) function and inside the pollFuncs.getPollfromResultRow(row); function
Bot is listening on port 3000
undefined
undefined
(node:14000) UnhandledPromiseRejectionWarning: TypeError: Cannot destructure property `id` of 'undefined' or 'null'.
at Object.getPollfromResultRow (C:\Users\ztb0504\Documents\Projects\Node\werewolfmod\pollFunctions.js:97:125)
at db.findOne.then (C:\Users\ztb0504\Documents\Projects\Node\werewolfmod\index.js:59:56)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:14000) 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:14000) [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.
DBRes:
{ id: '22',
poll_title: 'This is a new Pollstgresql',
//The rest of the expected data....
}
I'd appreciate any guidance on how to get this to return data as expected.
Thank you!
You're mixing plain callbacks and promises and it is causing you problems. It will be a lot easier if you don't do that.
If you pass a plain callback to db.query(), then it won't return a promise. In fact, it will return nothing (undefined). So, when you do return db.query(), all you're doing is returning undefined.
Change to this:
const findOne = async (req) => {
const { teamId, channelId, isClosed } = req;
return db.query('SELECT * FROM polls where team_id= $1 and channel_id =$2 and is_closed = $3 LIMIT 1',
[teamId, channelId, isClosed]).then(results) => {
console.log("\nDBRes: \n", results.rows[0])
return results.rows[0];
});
};
The, you also need error handling in your request handler if there are any errors in the query. Promise handling should nearly always have a .catch() somewhere to handle errors:
case 'results':
db.findOne({
teamId: requestBody.team_id,
channelId: requestBody.channel_id,
isClosed: false,
}).then((row) => {
console.log(row);
const poll = pollFuncs.getPollfromResultRow(row);
const displayText = pollFuncs.getFormattedPollResults(poll);
res.status(200).send({
text: displayText,
});
}).catch(err => {
console.log(err);
res.sendStatus(500);
});
break;

UnhandledPromiseRejectionWarning when using a SoapClient

I am new in node.js, and I am experimenting things recently. A few days ago, I have tried to send a XML request to an API, with the use of easysoap-request. It worked perfectly, but I would have had to create an XML file for each different query, so I tried with easysoap. I found myself stuck pretty quickly, but I managed to resolve some issues with the help of this website. Now my program give an error that I have trouble understanding. Here my code first:
const EasySoap = require('easysoap');
const request = (async () => {
const params = {
host : 'https://someapi.com',
path : '/dir/soap',
wsdl : '/dir/wsdl',
headers: [{
'user-agent': 'Request-Promise',
'Content-Type': 'text/xml',
}]
}
var soapClient = EasySoap(params);
soapClient.call({
method :'one_methode',
attributes: {
xmlns: 'https://someapi.com'
},
params: {
'api' : {
'authentication' : {
'login' : 'mylogin',
'password' : 'mypassword'
},
'params' : {
'another_params' : {
'name' : 'Brian',
}
}
}
}
}).then((callResponse) => {
console.log(callResponse.data); // response data as json
console.log(callResponse.body); // response body
console.log(callResponse.header); //response header
}).catch((err) => {
throw new Error(err);
});
});
request();
And the error it give me:
node:10264) UnhandledPromiseRejectionWarning: Error: Error: no wsdl/xml response at soapClient.call.then.catch (C:\Users\user\Documents\src\script.js:40:15) at process._tickCallback (internal/process/next_tick.js:68:7) (node:10264) 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:10264) [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.
Is this a problem with the .catch() ? Can someone explain me ? Thanks
It's because you're throwing error inside catch, which is wrapped to Promise.reject since it's thrown inside async function, and not catching anywhere.
...
}).catch((err) => {
throw new Error(err);
});
You can either handle the error in that block like console.error(err)
or handle in your request() function call like
// request returns promise since you wrapped it in async function
request()
.catch(err => console.error(err))

Module Promise: UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'collection' of undefined

i just searched for my problems around in the stackoverflow's discussions but nothings similar with my issued. So, in this case, i just want to update my collection and then use the 'Promise' module instead use the callbacks / anonymous functions as normally i did. but the error comes up when I execute the js's application in cmd.
Here my simple code:
var Promise = require('promise'); // use the 'promise' module
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost/EmployeeDB';
MongoClient.connect(url)
.then(function(err, db) {
db.collection('Employee').updateOne({
"EmployeeName": "Jeffrey"
}, {
$set: {
"EmployeeName": "Jeffrey Scurgs"
}
});
});
and the error results when i executed the code in cmd:
(node:8600) UnhandledPromiseRejectionWarning: TypeError: Cannot read
property 'collection' of undefined
at C:\Users\DELL\guru99\5_Promise\app_promise.js:7:9
at
at process._tickCallback (internal/process/next_tick.js:189:7) (node:8600) 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:8600) [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.
so, is there any wrong code in my code above?
thanks for helping...
sorry for my bad english
Your approach is correct but you a missed one thing.
When you don't provide callback parameters mongo ORM return a promise. Here is the corrected code:
MongoClient.connect(url)
.then(function(db) { // <- db is first argument
db.collection('Employee').updateOne({
"EmployeeName": "Jeffrey"
}, {
$set: {
"EmployeeName": "Jeffrey Scurgs"
}
});
})
.catch(function (err) {})
The db variable can only be undefined if there was an error connecting to the database.
You need to check and fix any error shown. You can also share the error
var Promise = require('promise'); // use the 'promise' module
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost/EmployeeDB';
MongoClient.connect(url)
.then(function(err, db) {
if (err) {
return throw err; // Check the error
}
db.collection('Employee').updateOne({
"EmployeeName": "Jeffrey"
}, {
$set: {
"EmployeeName": "Jeffrey Scurgs"
}
});
});

NodeJS: Unhandled promise rejection

I'm having a little problem and after debugged all the app I noticed that this is the file that's causing the problem, returning me a UnhandledPromiseRejection
'use strict'
const connection = require('../models/'),
oracledb = require('oracledb'),
conexion = oracledb.getConnection(connection)
oracledb.outFormat = oracledb.OBJECT;
module.exports = {
index(req, res) {
conexion.then(con => {
return con.execute(
`SELECT id_application, name, description, creation_date ` +
`FROM application `
).then(bucket => {
return con.execute(
`SELECT id_definition, id_application, field_name_original, field_name_new,
column_name, position, id_type_data, field_size, creation_date,
description, filter, visible ` +
`FROM definition `
).then(definitions => {
res.status(200).json(creaJSON(bucket, definitions))
}).catch(error => { return res.status(500).json({'message': error}) })
}).catch(err => { return res.status(500).json({'message': err}) })
}).catch(err => { return res.status(500).json({'message': err}) })
},
create(req, res) {
},
update(req, res) {
}
}
const doRelease = (connection) => {
connection.close((err) => {
if(err) console.error(err.message);
})
}
const creaJSON = (buckets, definitions) => {
var df = new Array()
buckets['rows'].map(obj => {
definitions['rows'].map(def => {
if(obj['ID_APPLICATION'] == def['ID_APPLICATION']) df.push(def)
})
obj['Definitions'] = df
df = []
})
return buckets.rows
}
after the UnhandledPromiseRejection is being followed by: Error: ORA-12170: TNS:Connect timeout occurred
(node:1270) 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 already looked for solutions, some says that promises are not catching correctly but I don't see any problem with them. Any other suggestion?
Any help will be welcome.
Thanks
const connection = require('../models/'),
oracledb = require('oracledb'),
conexion = oracledb.getConnection(connection)
is setting conexion to the promise returned by a call to .getConnection made when the entire source file is executed (in response to being required).
conexion has no handlers at this point. Handlers are only added later when the indexmethod of the exported {index, create, update} object is called.
Hence connection timeout in between the source file being required and index being called will produce an unhandled rejection error.
Obviously adding a catch clause such as
conexion = oracledb.getConnection(connection).catch( onRejected)
should fix this error, but how much recovery you want to put into coding onRejected is up to you.
Edit:
A less obvious approach to satisfying V8's version of how to handle uncaught promise rejection is to provide a dummy handler to thwart it:
conexion = oracledb.getConnection(connection);
conexion.catch(()=>undefined); // a do nothing catch handler.
Here the second line adds a handler to the conexion promise, making it "handled", which prevents it ever becoming an uncaught promise rejection. The promise returned by catch is superfluous and not recorded, but will be fulfilled if the no-operation catch handler is ever called.
Now the promise held in conexion can be rejected before index is called without generating an exception. Whether this is the best way to code promise topology for a particular application is a different question - you may very well wish to address a connection timeout earlier.

UnhandledPromiseRejection in Express.js

I hope I'm supplying enough information for this question, but I can't understand why my callback function returns Unhandled Promise Rejection when I on purpose want to catch the error:
(node:3144) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Can't set headers after they are sent.
(node:3144) 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'm calling the function here in routes:
router.route("/home/create")
.post(Authorization, function(req, res) {
CreateSnippetResource(req, function(err) {
if (err) {
console.log(err.message)
}
res.redirect("/home")
});
});
And the "CreateSnippetResource"-function:
(function() {
let User = require("../../Models/User");
let Snippet = require("../../Models/Snippet");
/**
* Create a new snippet and save it to database
* #param request
* #param callback
*/
module.exports = function(request, callback) {
callback(
User.findOne({ user: request.session.Auth.username }, function(err, user) {
if (err || user === null) {
callback("User not found")
}
var snippet = new Snippet({
title: request.body.snippetName.split(".").shift(),
fileName: "." + request.body.snippetName.split(".").pop(),
postedBy: user._id,
snippet: [{
text: " "
}]
});
snippet.save().then().catch(function(err) {
callback(err)
});
}))
};
}());
I'm trying to handle the error when title is not entered. I have a validator in my schema-module that looks like this:
SnippetSchema.path("title").validate(function(title) {
return title.length > 0;
}, "The title is empty");
And indeed the returned error-message from the callback CreateSnippetResource is The title is empty. So how come I get this Promise-error?
I'm assuming it has something to do with how I handle the snippet.save(), but can't see how it's not handled. Can you please help?
Why does my callback function return Unhandled Promise Rejection when I on purpose want to catch the error?
That will happen when your callback throws another exception. This will reject the promise returned by the .catch(…) call, and that rejection is nowhere handled.
As it turns out, I was an idiot, and forgot that I accidentally putted the whole function in the callback. The callback is then executed twice, and thus returns Error: Can't set headers after they are sent.

Categories

Resources