(node:2072) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'send' of undefined Discord js | Mongoose | MongoDB - mongodb

I am trying to make a simple welcome message on discord js with an event handler. It would work if I do it on the main file, but it does not work when I try it here. Code Below:
const profileModel = require('../../database/models/profileSchema');
let WelcomeSchema = require(`../../database/models/welcomeSchema`)
const Discord = require(`discord.js`)
const mongoose = require(`mongoose`)
module.exports = (client, member, GuildMember) => {
WelcomeSchema.findOne({ guildID: member.guild.id}, async (err, data, user) => {
console.log(member.guild.id)
if(!data) return;
const channel = await client.channels.cache.find(x => x.id === `${data.WelcomeChannel}`)
channel.send(`Welcome ${member}, ${data.WelcomeMsg}`)
})
}
Below Is My Event Handler (keep in mind the code above had the file name of, guildMemberAdd)
fs.readdirSync(`./events`).forEach(dirs => {
const events = fs.readdirSync(`./events/${dirs}`).filter(file => file.endsWith(`.js`))
for (const file of events) {
console.log(`Loading discord.js event ${file}`);
const event = require(`./events/${dirs}/${file}`);
client.on(file.split(".")[0], event.bind(null, client));
}
});
Below Is The Full Error
(node:2072) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'send' of undefined
at E:\Software\Github Repository shit\EA-BOT\events\Other\guildMemberAdd.js:15:13
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(node:2072) 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:2072) [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.
Below Is Line 15 (where the error was at)
(line 14) const channel = await client.channels.cache.find(x => x.id === `${data.WelcomeChannel}`)
(line 15) channel.send(`Welcome ${member}, ${data.WelcomeMsg}`)

The error is self-explanatory. Cannot read property 'send' of undefined you are attempting to invoke .send() method of something undefined - meaning channel is undefined. If we take a look at line 14, the logical explanation is that there is no channel, for which
x.id === `${data.WelcomeChannel}`
is true.
The line if (!data) return; for your purposes is not specific enough. It appears data exists, but either data.WelcomeChannel does not, or IDs don't much.
Try to use line if (!data.WelcomeChannel) return; and see if this exits your code. Then double-check data.WelcomeChannel is a correct channel id (and if it's actually an id, not channel object).

Instead of using this:
const channel = await client.channels.cache.find(x => x.id === `${data.WelcomeChannel}`)
to get your Discord.channel, try doing this:
const channel = await client.channels.cache.get(data.WelcomeChannel)
Note: I can't test the fix myself because I'm currently in school, but this may fix your issue.

Related

ERR_UNHANDLED_REJECTION

node:internal/process/promises:279
triggerUncaughtException(err, true /* fromPromise */);
^
[UnhandledPromiseRejection: 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(). The promise rejected with the reason "AxiosError: Request failed with status code 403".] {
code: 'ERR_UNHANDLED_REJECTION'
}

How to execute different error messages depending on where a query failed in a transaction in pg-promise?

how can I execute varying error messages depending on where a query failed, triggering a rollback, in my transaction?
I'll be using the sample code from the documentation:
db.tx(t => {
// creating a sequence of transaction queries:
const q1 = t.none(query);
const q2 = t.one(query);
const q3 = t.one(query);
// returning a promise that determines a successful transaction:
return t.batch([q1, q2, q3]); // all of the queries are to be resolved;
})
.then(data => {
// success, COMMIT was executed
})
.catch(error => {
// failure, ROLLBACK was executed
});
Preferred output is the following:
if the transaction failed in q1:
res.json({error: true, message:"q1 failed"})
if the transaction failed in q2:
res.json({error: true, message:"q2 failed"})
if the transaction failed in q3:
res.json({error: true, message:"q2 failed"}), etc.
What I'm thinking is using a Switch statement to determine what error message to execute, although I don't have an idea on how to know what query failed in the transaction.
Thank you for your help!
P.S. I recently migrated from node-pg to pg-promise (which is why I'm a bit new with the API) due to having a hard time with transactions as recommended in my previous posts, and yeah, pg-promise made a lot of things easier the 1 day worth of refactoring code is worth it.
Since you are using method batch, you get BatchError thrown when the method fails, which has useful property data, among others:
.catch(err => {
// find index of the first failed query:
const errIdx = err.data.findIndex(e => !e.success);
// do what you want here, based on the index;
});
Note that inside such error handler, err.data[errIdx].result is the same as err.first, representing the first error that occurred.

Receive commands from a specific channel

How can I make the bot receive commands from specific channels, and if there is no channel, it is received from all channels and it is connected to mongoDB?
I can do the receiving command from a specific channel using channel ID, but I want via the command:
!setChannel #ID_CHANNEL OR mention
I tried these codes
let channel = message.mentions.channels.first()
if(!args[0]) return message.channel.send('Please Mention Channel');
if(!channel) return message.channel.send('Please Mention Vaild Channel');
/*-----------------------------in mongedb add Guild id + channel id------------------------------
in quick.db it is like this -->
db.set("commands_channel_"+ message.guild.id + channel.id, true)*/
message.channel.send(`Commands Channel: ${channel}`);
let CommandsChannel = db.get("commands_channel_"+ message.guild.id + channel.id)
if(!CommandsChannel) return
//-------------------------------//
if(CommandsChannel = true) {
// else command code //
}
wrong with the code
(node:4456) UnhandledPromiseRejectionWarning: Error: `commands_channel_708596988995829762709436321805893753` is an invalid option.
at Mongoose.set (/rbd/pnpm-volume/34e95e32-ea3c-4e44-8fb4-6f803dcbc088/node_modules/.registry.npmjs.org/mongoose/5.10.15/node_modules/mongoose/lib/index.js:179:48)
at Object.run (/app/commands/admin/setchannel.js:19:10)
at module.exports (/app/events/message.js:152:17)
at processTicksAndRejections (internal/process/task_queues.js:88:5)
(node:4456) 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)

Protractor isDisplayed has no .catch, leading to UnhandledPromiseRejectionWarning

Then "Thenable" returned by ElementFinder.isDisplayed has no catch.
let promise = element(by.css('donut')).isDisplayed();
console.log(promise.then); // => (fn, errorFn) => ...
console.log(promise.catch); // => undefined
If I use try-catch in an async function:
try {
await e.isDisplayed();
} catch (e) {
console.log(e);
}
I do catch the exception, but then I get an UnhandledPromiseRejectionWarning from Node, with a deprecation warning:
(node:12296) UnhandledPromiseRejectionWarning: NoSuchElementError: No element found using locator: By(css selector, donut)
...
(node:12296) [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.
How can handle that promise rejection? I can't use .catch on the value returned by isDisplayed, and apparently using a try-catch in an async function isn't enough.
NOTE: I'm aware that I can use e.isPresent() to find out in advance if e.isDisplayed() will throw, but the question is not how to avoid this error, but why it cannot be caught.

flutterBlue.connect(device, timeout: const Duration(seconds: 10),).listen(null); in flutter

sorry,I am a beginner and my English is very bad
i have a trouble in Flutter.
i reference https://pub.dartlang.org/packages/flutter_blue
I want to use flutter to communicate with the ear thermometer device.
when i reopen bluetooth and it can work,but I reopen app and excute second it show error.
i guess bluetooth gatt cahce is causing a error.
how can i solve it?
my code
deviceConnection = flutterBlue.scan(timeout: const Duration(seconds: 5),).listen((scanResult) async {
device = scanResult.device;
deviceConnection2 = await flutterBlue.connect(device, timeout: const Duration(seconds: 10),).listen(null);//this line error is error 1
deviceStateSubscription = device.onStateChanged().listen((s) async {
await device.discoverServices().then((s) async {//this is error 2
.........
}
}
}
it show these error
error 1
Dart Error: Unhandled exception:
PlatformException(already_connected, connection with device already exists, null)
error 2
Dart Error: Unhandled exception:
PlatformException(get_services_error, no instance of BluetoothGatt, have you connected first?, null)
Error 1
Dart Error: Unhandled exception: PlatformException(already_connected, connection with device already exists, null)
Since the app detected that a bluetooth device is already connected, one workaround is check for any connected device disconnect it. You can create a function that does this like the one in this GitHub thread:
What you can do here is that you check for any connected devices and
then disconnect them. I have written a function that does just that,
here it is:
checkConnectedDevices() async{
connectedDevices = await flutterBlue.connectedDevices.whenComplete((){
print(connectedDevices);
for(int i = 0; i < connectedDevices.length; i++){
connectedDevices[i].disconnect();
}
});
}
Error 2
Dart Error: Unhandled exception: PlatformException(get_services_error, no instance of BluetoothGatt, have you connected first?, null)
Since there is an error connecting to the device, you will not be able to call the discoverServices(). Because you need to be connected to a device before you can call this function. Check the following GitHub discussions related to this error:
connected ' discoverServices ' is't get #426
discoverServices is broken #535