Reputation: 57
I am trying to get channel with an id or mention, the code itself works but when user gives wrong ID it says: TypeError: Cannot read properties of undefined (reading 'catch')
Can anyone help me?
I tried this:
message.guild.channels.cache.find(channel => channel.id == args[0]).catch(err => {});
And this:
message.guild.channels.cache.get(args[0]).catch(err => {});
These both things give me error.
Heres the code:
if (args[0].startsWith("<#")) channel = message.mentions.channels.first();
else channel = message.guild.channels.cache.get(args[0]).catch(err => {
//do stuff
})
Upvotes: 1
Views: 20682
Reputation: 178
The error TypeError: Cannot read properties of undefined (reading 'catch')
means that you are calling catch
on undefined
.
Basically, it's undefined.catch()
.
Assuming you are working with promises, this can happen when a method that's being called is not present in the object.
e.g
const myObj = {
fun1: async () => {
const res = await callingExternalFun();
if (res.error) {
throw new Error('my error');
}
},
};
myObj.fun1().catch((e) => {console.log(e.message)}); // my error
myObj.fun2().catch((e) => {console.log(e.message)}); // TypeError: Cannot read properties of undefined (reading 'catch')
Here, myObj has async function fun1
that might return an error. So the .catch
here comes from Promise.prototype.catch()
However, myObj
doesn't have a function fun2
, it's undefiend
and catch
will return this error.
Upvotes: 0
Reputation: 57
Okay so i found out the answer with help of @JeremyThille: `When the id is wrong it tries to null.catch()
I removed catch from the code and added
if(!channel) //do stuff
Thanks @JeremyThille
Upvotes: 2