Cannot resolve error unhandled promise rejection and NoSuchSessionError - javascript

I am trying to build some code but I get those two errors:
(node:12909) UnhandledPromiseRejectionWarning: NoSuchSessionError: Tried to run command without establishing a connection
at Object.throwDecodedError (/home/matthew/node_modules/selenium-webdriver/lib/error.js:550:15)
at parseHttpResponse (/home/matthew/node_modules/selenium-webdriver/lib/http.js:563:13)
at Executor.execute (/home/matthew/node_modules/selenium-webdriver/lib/http.js:489:26)
at
at process._tickCallback (internal/process/next_tick.js:188:7)
(node:12909) 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:12909) [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:12909) UnhandledPromiseRejectionWarning: NoSuchSessionError: Tried to run command without establishing a connection
at Object.throwDecodedError (/home/matthew/node_modules/selenium-webdriver/lib/error.js:550:15)
at parseHttpResponse (/home/matthew/node_modules/selenium-webdriver/lib/http.js:563:13)
at Executor.execute (/home/matthew/node_modules/selenium-webdriver/lib/http.js:489:26)
at
at process._tickCallback (internal/process/next_tick.js:188:7)
(node:12909) 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)
function review_balance() {
if (balance_amount > 0) {
console.log("This address has " + balance_amount + "Bitcoin");
}
else {
console.log("0 Bitcoins!");
}
}
async function searching() {
console.log("Waiting for address to be scanned on the Bitcoin blockchain...");
const result = await review_balance();
console.log(result);
}
searching();
driver.close();
This is the part of the program that is the most important and contains the problem. Can anyone give me any advice? I would be really thankful.

Solution using Promise:
let check_balance = new Promise((resolve, reject) => {
driver.get("https://explorer.bitcoin.com/btc/address/" + address);
let balance_amount = driver.findElement(webdriver.By.className("amount")).getText();
if (balance_amount > 0) {
resolve('This wallet has ' + balance_amount + ' Bitcoins.');
}
else {
reject('0 Bitcoins!');
}})check_balance.then((message) => {
console.log(message);}).catch((message) => {
console.log(message);}) setTimeout(function () {
driver.quit();}, 8000);

Related

How to throw an exception from a Promise to the Caller without an UnhandledPromiseRejectionWarning

Consider this database query handler that does contain a catch block:
async function dml(pool, sql, expected = -1) {
p(sql)
let rowCnt = await pool.query(sql)
.then(r => {
if (expected >= 0 && r.rowCount != expected) {
throw `DML [${sql}] had wrong number of results: ${r.rowCount} vs expected=${expected}`
} else {
return r.rowCount
}
})
.catch(err => {
msg = `Query [${sql}] failed: ${err}`;
printError(msg,err)
throw msg // THIS is the problem. It generates UnhandledPromiseRejection
}
return rowCnt
}
The thrown exception is intended to be caught by the caller here:
async function handleClip(data) {
..
// calling code
try {
// ...
let cnt = db.dmlClips(sql, 1) // Throw() happens in this invocation
debug(`Update count is ${cnt}`)
return rcode
} catch (err) {
// WHY is the thrown exception not caught here??
let msg = `Error in handleClip for data=${data.slice(0,min(data.length,200))}`;
error(msg,err);
}
But the above structure is not acceptable apparently: the following serious warning is generated:
(node:39959) UnhandledPromiseRejectionWarning: Query [insert into clip ...] failed: error: role "myuser" does not exist
at emitUnhandledRejectionWarning (internal/process/promises.js:170:15)
at processPromiseRejections (internal/process/promises.js:247:11)
at processTicksAndRejections (internal/process/task_queues.js:94:32)
(node:39959) 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:39959) [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.
at emitDeprecationWarning (internal/process/promises.js:180:11)
at processPromiseRejections (internal/process/promises.js:249:13)
at processTicksAndRejections (internal/process/task_queues.js:94:32)
So how does this need to be set up ? Note there is a related question here: how to properly throw an error if promise is rejected? (UnhandledPromiseRejectionWarning) . But for that question the asker did not have any exception handler/catch block.
You need to use await when you're calling the function db.dmlClips(sql, 1) so that it waits for the promise to be resolved/rejected. Change the line to let cnt = await db.dmlClips(sql, 1).
It looks like the try-catch block from which you are invoking db.dmlClips isn't inside an async function. Try-catch declared in functions without async keywords won't catch a promise rejection.

When I run a script it tells me that filter is not a function. [Discord.js]

I have a script where you need to answer to the bot with yes (da in the script) or no (nu in the script) and when I run the script on discord it tells me that filter is not a function. I have to mention that I am a beginner.
The script is this:
module.exports = {
name: 'moneda',
description: 'mai usor de luat o decizie',
execute(message, args){
let decizii = [
"Fata",
"Spate",
]
let decizie = decizii[Math.floor(Math.random() * (decizii.length))]
message.reply(`Ti-a picat ${decizie}`);
let decizii1 = [
"Fata",
"Spate",
]
let decizie1 = decizii1[Math.floor(Math.random() * (decizii1.length))]
message.channel.send('Mai vrei sa incerci odata?').then(async (start) => {
message.channel.awaitMessage(filter, { maxMatches: 1, time: 60000, errors: ['time']}).then(async (collected) => {
if(collected.first().content === 'da') {message.channel.send(decizie1)} else if (collected.first().content === 'nu') {return}
})
})
}
}
The error is this:
(node:8340) UnhandledPromiseRejectionWarning: ReferenceError: filter is not defined
at C:\Users\ADRIAN\Desktop\ZerOne BOT\commands\moneda.js:18:42
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:8340) 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: 2)
(node:8340) [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.
filter is not defined, means that you have to create a filter.
This is an example filter, for your problem:
let filter = m => m.author.id === message.author.id;

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.

Jimp error: No matching constructor overloading was found

I'm trying to create a meme command with my bot that uses Jimp to add text onto an image the user sends with the command. It works, but whenever something doesn't go to plan (e.g. someone not sending the image, someone not sending the text that needs to be applied to the image, etc.) it gets an error and crashes my bot. Here's my code:
case "meme":
const [topText, bottomText] = args.slice(1).join(" ").split(",");
msg.channel.startTyping();
if (!args[1]) msg.channel.send("You need to give the text you want to apply to the image!");
Jimp.read(msg.attachments.first(), (err, lenna) => {
Jimp.loadFont(Jimp.FONT_SANS_128_WHITE).then(font => {
if (err) console.log(err);
lenna
.resize(1280, 1080)
.quality(100) // set quality
.print(font, 75, 20, {
text: topText,
alignmentX: Jimp.HORIZONTAL_ALIGN_CENTER,
alignmentY: Jimp.VERTICAL_ALIGN_MIDDLE
}, 1100)
.print(font, 75, 900, {
text: bottomText,
alignmentX: Jimp.HORIZONTAL_ALIGN_CENTER,
alignmentY: Jimp.VERTICAL_ALIGN_MIDDLE
}, 1100)
.write("./tmp/" + msg.author.id + ".jpg"); // save
});
});
for (i = 0; i < (1); i++) {
setTimeout(function () {
msg.channel.send({
files: ["./tmp/" + msg.author.id + ".jpg"]
})
msg.channel.stopTyping();
for (i = 0; i < (1); i++) {
setTimeout(function () {
fs.unlinkSync("./tmp/" + msg.author.id + ".jpg")
}, 3 * 1000)
}
}, 3 * 1000)
}
break;
Error:
(node:32440) UnhandledPromiseRejectionWarning: Error: No matching constructor overloading was found. Please see the docs for how to call the Jimp constructor.
at Jimp.throwError (C:\Users\lqshkiwi\Desktop\Discord Bot\node_modules\#jimp\utils\dist\index.js:35:13)
at new Jimp (C:\Users\lqshkiwi\Desktop\Discord Bot\node_modules\#jimp\core\dist\index.js:502:85)
at _construct (C:\Users\lqshkiwi\Desktop\Discord Bot\node_modules\#babel\runtime\helpers\construct.js:19:21)
at C:\Users\lqshkiwi\Desktop\Discord Bot\node_modules\#jimp\core\dist\index.js:1016:32
at new Promise (<anonymous>)
at Function.Jimp.read (C:\Users\lqshkiwi\Desktop\Discord Bot\node_modules\#jimp\core\dist\index.js:1015:10)
at Client.<anonymous> (C:\Users\lqshkiwi\Desktop\Discord Bot\index.js:53:18)
at Client.emit (events.js:310:20)
at MessageCreateAction.handle (C:\Users\lqshkiwi\Desktop\Discord Bot\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\lqshkiwi\Desktop\Discord Bot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
(node:32440) 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:32440) [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:32440) UnhandledPromiseRejectionWarning: Error: ENOENT: no such file or directory, stat 'C:\Users\lqshkiwi\Desktop\Discord Bot\tmp\652940695585292299.jpg'
(node:32440) 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: 2)
internal/fs/utils.js:230
throw err;
^
Error: ENOENT: no such file or directory, unlink './tmp/652940695585292299.jpg'
at Object.unlinkSync (fs.js:1053:3)
at Timeout._onTimeout (C:\Users\lqshkiwi\Desktop\Discord Bot\index.js:80:32)
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7) {
errno: -4058,
syscall: 'unlink',
code: 'ENOENT',
path: './tmp/652940695585292299.jpg'
}
Without know what specific error you're trying to handle against, the best way is to wrap your entire section of code in a try/catch. In the catch portion, you can console.warn the error and hopefully use the logs to debug this with more details.
You forgot to add a return statement to exit the logic if the user didn't follow the proper commands. When the user didn't provide the argument, I'm guessing msg.attachments.first() returns undefined which is why Jimp errors.
if (!args[1]) {
return msg.channel.send("You need to give the text you want to apply to the image!");
}
try { // it's good to have a try catch when dealing with asynchronous code
Jimp.read(msg.attachments.first(), (err, lenna) => {
...

Using sql.each with async callback

I am using the sqlite module from npm (not sqlite3).
I need to use an async function on each row of the database. However any async code is causing an error.
The following snippet
async function scanDatabase() {
console.log("Scanning database...");
sql
.each(`SELECT * FROM users`, async function(err, row) {
if (err) console.log(err);
console.log(row);
let member = await guild.fetchMember(row.id);
console.log(member);
console.log(row.id);
console.log(member.user.username);
})
.then(function() {
console.log("finished scanning the database");
});
}
Yields the following:
Scanning database...
{ id: 119351283999047680,
first_payment: '2018-03-09T11:26:26.989Z',
last_payment: '2018-03-09T12:56:19.784Z',
expires: '2018-03-16T10:26:26.987Z' }
(node:12292) UnhandledPromiseRejectionWarning: Unhandled promise rejection
(rejection id: 2): Error: Invalid or uncached id provided.
(node:12292) [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.
finished scanning the database
I get the unhandled promise errors, but I don't know how to fix " Error: Invalid or uncached id provided."

Categories

Resources