Cant read property 'get' of undefined in nodejs - node.js

I am using Neo4j for the first time with nodejs and developing an application. I am getting the following error. I tried my best. Can you please help me with this error?
Error
(node:16148) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'get' of
undefined
at E:\fyps\app.js:120:33
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:16148) 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:16148) [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.
code
app.get('/person/:id',function(req,res){
var id = req.params.id;
session
.run("MATCH (a:Person) WHERE id(a)=$idParam RETURN a.name as name", {idParam: id})
.then(function(result){
var name =result.records[0].get("name");
session
.run("OPTIONAL MATCH (a:Person)- [r:BORN_in]-(b:location) where id(a)=$idParam RETURN b.city as city, b.state as state" , {idParam:id})
.then(function(result2){
var city =result2.records[0].get("city");
var state =result2.records[0].get("state");
session
.run("OPTIONAL MATCH (a:Person)-[r:FRIENDS]-(b:Person) WHERE id(a)=$idParam RETURN b", {idParam:id})
.then(function(result3){
var friendsArr =[];
result3.records.forEach(function(record){
if(record._fields[0] != null){
friendsArr.push({
id: record._fields[0].identity.low,
name: record._fields[0].properties.name
});
}
})
res.render('person',{
id:id,
name:name,
city:city,
state:state,
friends:friendsArr
})
session.close();
})
.catch(function(error){
console.log(error);
})
can you please help me that how to solve this error.. Thanks

The error message clearly says that you are calling the get function on some entity that is undefined, and that has happened within a Promise. So, the error statement can be any one of these:
var name =result.records[0].get("name");
var city =result2.records[0].get("city");
var state =result2.records[0].get("state");
Add some relevant log statements to check which one is causing the issue.

Related

Error creating database pool not creating session

Development environment: nodejs
Library: oracle-db
Oracle Version : 9i
The test and error occurrence codes are as follows:
const oracledb = require("oracledb");
async function hello() {
await oracledb.createPool({
user: "test",
password: "1234", // myhrpw contains the hr schema password
connectString: "127.0.0.1/ORCL",
poolAlias: "ora1",
poolIncrement: 0,
poolMax: 4,
poolMin: 4,
poolPingInterval: 30,
});
const connection = await oracledb.getConnection("ora1");
const result = await connection.execute(`SELECT IDX FROM MYTABLE WHERE number= '000000000'`);
console.log(result.rows);
connection.release();
}
hello();
The database pool was created with this code. And after the test, four sessions were created and confirmed to work well. However, an error occurred due to repeated execution of the code. If only three or fewer sessions are created when creating the pool, the following error occurs:
(node:27732) UnhandledPromiseRejectionWarning: Error: ORA-12170: TNS:Connect timeout occurred
(node:27732) 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:27732) [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.
In order to check what kind of error has occurred, I have tailed the file below.
#tail -f /oracle/app/oracle/admin/orcl/bdump/alert_orcl.log
#tail -f /oracle/app/oracle/product/9i/rdbms/log/alert_orcl.log
However, no logs were stacked and no errors were seen. Could you possibly help me?

Discord.js v12 server member count

(Welcome command using canvas)
How could I fetch the server member count as soon as someone joins??
Because I use that line of code
const guild = client.guilds.cache.get("843190900930510869");
let image = await welcomeCanvas
.setUsername(member.user.tag)
.setDiscriminator(member.user.discriminator)
.setMemberCount(guild.memberCount) //this line
etc...
And well, it just doesn't send the image..
Error:
(node:6387) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'memberCount' of undefined
at GuildMemberAddListener.exec (/app/listeners/guildMemberAdd.js:100:29)
(node:6387) 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:6387) [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.
The event client.on('guildMemberAdd', () => {}) will return a GuildMember object. Simply use this GuildMember object to get the guild they entered GuildMember.guild then check if that guild is available to the client using guild.available. If it is available you can access all the properties on that guild including the guild.memberCount property.
client.on('guildMemberAdd', (member) => {
const guild = member.guild
if (!guild.available) return console.error('Uh Oh Stinky...')
const guildMemberCount = guild.memberCount
console.log(guildMemberCount)
})

Selenium Grid returns 504 errors in console

I'm building a Selenium Grid systems in Kubernetes with Chrome and Firefox nodes and a hub.
The tests goes well with 3 times invoke or 6 sessions in queue. But when it goes higher, the console will return a 504 error. Here is the code:
let driver = new Builder()
.usingServer("https://example.com/")
.withCapabilities(capabilities)
.setChromeOptions(chromeOptions)
.build();
try {
console.log("Execution Start..............", Date());
await driver.get('http://www.google.com');
console.log("After get..............", Date());
// Enter text "cheese" and perform keyboard action "Enter"
await driver.findElement(By.name('q')).sendKeys('tester', Key.ENTER);
console.log("After findElement..............", Date());
let firstResult = await driver.wait(until.elementLocated(By.css('h3')), 10000);
console.log("Before firstResult..............", Date());
console.log(await firstResult.getAttribute('textContent'));
console.log("After firstResult..............", Date());
} finally {
console.log("Execution end..............", Date());
await driver.quit();
}
}
And here is the output:
Execution end.............. Sun Dec 19 2021 19:39:11 GMT+0700 (Indochina Time)
(node:96313) UnhandledPromiseRejectionWarning: WebDriverError: <html>
<head><title>504 Gateway Time-out</title></head>
<body>
<center><h1>504 Gateway Time-out</h1></center>
<hr><center>nginx</center>
</body>
</html>
at parseHttpResponse (/SeleniumGrid/node_modules/selenium-webdriver/lib/http.js:664:11)
at Executor.execute (/SeleniumGrid/node_modules/selenium-webdriver/lib/http.js:573:28)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:96313) 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: 6)
(node:96313) [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.
(node:96313) UnhandledPromiseRejectionWarning: WebDriverError: <html>
<head><title>504 Gateway Time-out</title></head>
<body>
<center><h1>504 Gateway Time-out</h1></center>
<hr><center>nginx</center>
</body>
</html>
at parseHttpResponse (/SeleniumGrid/node_modules/selenium-webdriver/lib/http.js:664:11)
at Executor.execute (/SeleniumGrid/node_modules/selenium-webdriver/lib/http.js:573:28)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
(node:96313) 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: 8)
I think the error appear and the await driver.get('http://www.google.com'); line. Does anyone know how to fix it?

ECONNREFUSED error when loading a TensorFlow frozen model from node.js

I was trying to load a TensorFlow fronzen model from a url that points to not existing resource to test my code robustness. However, even though I have set a catch, I am not able to manage a ECONNREFUSED that is raised internally by the function tf.loadFrozenModel.
Is there any possible mitigation to this issue? This is for me a critical problem, since it stops the execution of nodejs.
Here is the code where the error is generated.
global.fetch = require("node-fetch");
const tf = require("#tensorflow/tfjs");
require("#tensorflow/tfjs-node");
class TFModel {
...
loadFzModel(modelUrl, modelWeigths) {
return tf.loadFrozenModel(modelUrl, modelWeigths)
.then((mod) => {
this.arch = mod;
})
.catch((err) => {
console.log("Error downloading the model!");
});
}
...
}
Here instead are the errors I am getting:
UnhandledPromiseRejectionWarning: Error: http://localhost:30000/webModel/tensorflowjs_model.pb not found. FetchError: request to http://localhost:30000/webModel/tensorflowjs_model.pb failed, reason: connect ECONNREFUSED 127.0.0.1:30000
at BrowserHTTPRequest.<anonymous> (.../node_modules/#tensorflow/tfjs-core/dist/io/browser_http.js:128:31)
at step (.../node_modules/#tensorflow/tfjs-core/dist/io/browser_http.js:32:23)
at Object.throw (.../node_modules/#tensorflow/tfjs-core/dist/io/browser_http.js:13:53)
at rejected (.../node_modules/#tensorflow/tfjs-core/dist/io/browser_http.js:5:65)
at process.internalTickCallback (internal/process/next_tick.js:77:7)
(node:23291) 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:23291) [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.
Note: the code works if modelUrl and modelWeights are valid url pointing to existing resources.
Node-2: the code is executed as part of a custom block for Node-Red.
If you don't find any other solution you can catch the error on the top level like this:
process.on('uncaughtException', function (err) {
console.error(err);
});
In there you can get more specific to only catch your specific error.
This is in the process of being addressed at https://github.com/tensorflow/tfjs-core/pull/1455.

How to find which promises are unhandled in Node.js UnhandledPromiseRejectionWarning?

Node.js from version 7 has async/await syntactic sugar for handling promises and now in my code the following warning comes up quite often:
(node:11057) UnhandledPromiseRejectionWarning: Unhandled promise
rejection (rejection id: 1): ReferenceError: Error: Can't set headers
after they are sent.
(node:11057) 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.
Unfortunately there's no reference to the line where the catch is missing.
Is there any way to find it without checking every try/catch block?
listen unhandledRejection event of process.
process.on('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at: Promise', p, 'reason:', reason);
// application specific logging, throwing an error, or other logic here
});
The correct way to show a full stacktrace for unhandled ES6 Promise rejections, is to run Node.js with the --trace-warnings flag. This will show the full stacktrace for every warning, without having to intercept the rejection from within your own code. For example:
node --trace-warnings app.js
Ensure that the trace-warnings flag comes before the name of your .js file! Otherwise, the flag will be interpreted as an argument to your script, and it will be ignored by Node.js itself.
If you want to actually handle unhandled rejections (eg. by logging them), then you might want to use my unhandled-rejection module instead, which catches all the unhandled rejections for every major Promises implementation that supports it, with a single event handler.
That module supports Bluebird, ES6 Promises, Q, WhenJS, es6-promise, then/promise, and anything that conforms to any of the unhandled rejection specifications (full details in the documentation).
Logging with stack trace
If you are looking for more of a helpful error message. Try adding this to your node file. It should display the full stack trace where your crash is happening.
process.on('unhandledRejection', (error, p) => {
console.log('=== UNHANDLED REJECTION ===');
console.dir(error.stack);
});
This module allowed me to track down the culprit promise(s):
https://www.npmjs.com/package/trace-unhandled
Install
npm i trace-unhandled
Include in code
require('trace-unhandled/register');
#Jeremy I had same result, the reason variable provided by
process.on('unhandledRejection', (reason, p) => {});
wasn't defined and it take me time to figure out that there were promise rejection providing nothing in my code, typically:
new Promise((resolve reject) => {
const client = net.connect(options)
client.on("connect", () => {
resolve()
})
client.on("error", () => {
reject()
})
})
the problem is that you reject with nothing, to get trace you have to provide error, like this
new Promise((resolve reject) => {
const client = net.connect(options)
client.on("connect", () => {
resolve()
})
client.on("error", (err) => {
reject(err)
})
})
and if you don't have error you can provide one yourself, even if empty, it will give a stack trace
reject(new Error())
If you need to find where the error was throwed from, look in your code for Promise with empty rejection

Resources