So previously I have been using this following code to check if a member had a certain role.
if (message.member.roles.some(role => role.name === 'role'))
It always used to work for me. However, now it seems to return an error. I have narrowed it down, to message.member returning Null. I have tried changing it guildMember and the same issue.
the error in question is:
TypeError: Cannot read property 'roles' of undefined
Has there been any changes to this?
Can someone help me try to find a new way to check if they have a role?
Edit
This is where the message comes from
client.on('message', message => {
console.log("Member: " + message.member);
This returns null favlues for message.member.
Edit:
I've seen the console log for the 'message' object that you have shared in the comment and below is my update from that:
As we can see from the below image, message.member is 'null' due to which you were getting the error that you cannot find the property 'roles' of undefined (member which is null here).
I believe what you are looking for here is message.guild.roles here which is a collection (Map). Please see the screenshot below.
You should try to retrieve this roles Map and iterate over it for the in the following way:
const roles = message.guild.roles;
You can then use roles.entries() in order to get the key-value pairs from the roles MAP and iterate over them and use the if condition that you were initially using.
Like the error message states, this is happening because 'member' is undefined. You can either have a guard clause like mentioned by user Paulquappe in his answer, but the guard clause would be for member and not roles, so something like this:
if (message.member && message.member.roles.some(role => role.name === 'role'))
or, if you are going to transpile your code, you can use optional chaining from ES2020 (this is a very new feature in JS, therefore I would not recommend it unless you are going to transpile your code):
The optional chaining operator acts like a guard clause, but the syntax only requires that you use a '?' before chaining using the dot syntax.
if (message.member?.roles.some(role => role.name === 'role'))
Most likely there is no 'roles' prop on member. I suggest you create a guard clause and ensure the props is there before accesing it.
You can read about guard clause here:
How do you implement a guard clause in JavaScript?
Related
I am frequently running into situations where I have reactive statements that depend on multiple variables. Svelte does not wait to assign exported variable values from the calling component before reacting these statements, so I have to embedd all manner of checks on every variable to ensure they have been assigned before attempting to use them in a way that will raise a javascript error. Here's an example:
$: entityName = dimensionListing.includes((node?.synonyms??{})[node?.entityNameSynonym]) ? getAttr(data,node?.entityNameSynonym) : undefined
$: entityType = dimensionListing.includes((node?.synonyms??{})[node?.entityTypeSynonym]) ? getAttr(data,node?.entityTypeSynonym) : undefined
$: displayDimensions=node.entityAttributes.filter((e) => (dimensionListing??[]).includes(e.columnName) &&
e.columnName !== (node?.synonyms??{}[node?.entityNameSynonym]) &&
!(entityName && e.columnName === (node?.synonyms??{}[node?.entityTypeSynonym])) &&
data[e.columnName])
In the first example (entityName), it reacts as soon as dimensionListing gets assigned, but before node is assigned... it will raise a javascript error about reading from an undefined if it attempts to resolve "node.synonyms", so I have to use the ?. operator to avoid that. But then the .synonyms property will be undefined, which will in turn raise an error if I attempt to read it with [], so I have to coallesce undefines to an empty object {} to avoid that error. And lastly, ever reference to node. has to be made into node.?
Something similar is happening on the third assignment, of displayDimensions. When it executes I don't know if it's because Svelte assigned dimensionsListing, data, node, or the reactive entityName, all of which are dependencies. One of them will have an assignment, the other two or three will not. So I have to add all the ?. and ?? to avoid javascript errors until all the values are assigned and I get a good reactive statement execution on the third or fourth try.
This doesn't seem elegant or simple to code.
Another option is:
$: displayDimensions = node && dimensionListing && data && entityName ? *function* : undefined
This at least avoids using ?. and ?? in the function. But that's still not very satisfying, that I would to find, identity and list every single dependency like this before every reactive statement.
Is there not a simpler way to set "don't run this reactive statement unless all dependencies are defined" ?
You can put pretty much any arbitrary expression after $:. So you can just use an if statement:
<script>
let displayDimensions = undefined
$: if (node && dimensionsListing && data && entityName) {
displayDimensions = // Do your stuff
}
</script>
I hope this is satisfying to you because I'm pretty sure there isn't a way to have reactive values react to just some of the variables.
Maybe you could consider using onMount if the problem arises because of bind:this. It might be that with the nodes but without more context its hard to give a more tailored answer.
Hope this helps
I'm trying to read a JSON array. Every time i try to read the array/value by passing JSON object key like this-
json[key]
It shows a Eslint error-
[eslint] Generic Object Injection Sink (security/detect-object-injection)
I understand its a security warning because the key may not exists. But how do i resolve this warning? Is there any easier way to read the Json object. My plan is to pass the "key" to the function and read the json based on the key.
You are searching for an ES lint error fix:
Here is the syntax for it
json [`${key}`]
Example:
const obj = {
eventName: 'Music event',
landingPic: 'landing.jpg',
eventPic0: 'pic0.jpg',
eventPic1: 'pic1.jpg',
eventPic2: 'pic2.jpg',
eventPic3: 'pic3.jpg',
artist: 'Elie'
};
// array of keys which need to be read
const arrayOfKey = ['landingPic', 'eventPic0', 'eventPic1', 'eventPic2', 'eventPic3'];
// let's read the value by a key in array
arrayOfKey.forEach( key => {
const value = obj[`${key}`];
console.log(value);
});
There is a good answer here. In general this rule is for paranoiac and the article to which everyone appeal is a mislead. So the best answer, I would say is to turn this rule off, if you can for sure.
And another answer in the comments refers to eslint contributor answer that this rule is pretty false positive prone and more for human to audit a codebase(warning level) rather then give an error in a CI. So I would say you can totally ignore this rule or turn it off.
If you cannot turn it off or ignore, you can disable the eslint for line with comment that it's a false positive or use some interpolation as mentioned in other answers.
And finally, in order to destroy any doubts, the answer from creator of the rule:
"I'm the original author of this rule - for a bit of context, it was originally written as an assistive tool for manual code reviews, to be
used with the eslint plugin for VS Code. I would recommend disabling
it for other use cases, as it's just going to be far too noisy."
Unsure why, but typecasting the access parameter silences the error. Guessing this has something to do with sanitation being able to prevent pollution.
const myThing = myObj[String(key)]
const myThing = myObj[key as string]
What its trying to say is that using this notation:
You are able to modify even prototype properties of the object which is considered dangerous
By being able to modify everything, you are also able to modify the constructor (method/function) so it may be injected and then exploited.
The subject is described analytically here, providing a simple example:
https://web.archive.org/web/20150430062816/https://blog.liftsecurity.io/2015/01/15/the-dangers-of-square-bracket-notation
I'm trying to read a JSON array. Every time i try to read the array/value by passing JSON object key like this-
json[key]
It shows a Eslint error-
[eslint] Generic Object Injection Sink (security/detect-object-injection)
I understand its a security warning because the key may not exists. But how do i resolve this warning? Is there any easier way to read the Json object. My plan is to pass the "key" to the function and read the json based on the key.
You are searching for an ES lint error fix:
Here is the syntax for it
json [`${key}`]
Example:
const obj = {
eventName: 'Music event',
landingPic: 'landing.jpg',
eventPic0: 'pic0.jpg',
eventPic1: 'pic1.jpg',
eventPic2: 'pic2.jpg',
eventPic3: 'pic3.jpg',
artist: 'Elie'
};
// array of keys which need to be read
const arrayOfKey = ['landingPic', 'eventPic0', 'eventPic1', 'eventPic2', 'eventPic3'];
// let's read the value by a key in array
arrayOfKey.forEach( key => {
const value = obj[`${key}`];
console.log(value);
});
There is a good answer here. In general this rule is for paranoiac and the article to which everyone appeal is a mislead. So the best answer, I would say is to turn this rule off, if you can for sure.
And another answer in the comments refers to eslint contributor answer that this rule is pretty false positive prone and more for human to audit a codebase(warning level) rather then give an error in a CI. So I would say you can totally ignore this rule or turn it off.
If you cannot turn it off or ignore, you can disable the eslint for line with comment that it's a false positive or use some interpolation as mentioned in other answers.
And finally, in order to destroy any doubts, the answer from creator of the rule:
"I'm the original author of this rule - for a bit of context, it was originally written as an assistive tool for manual code reviews, to be
used with the eslint plugin for VS Code. I would recommend disabling
it for other use cases, as it's just going to be far too noisy."
Unsure why, but typecasting the access parameter silences the error. Guessing this has something to do with sanitation being able to prevent pollution.
const myThing = myObj[String(key)]
const myThing = myObj[key as string]
What its trying to say is that using this notation:
You are able to modify even prototype properties of the object which is considered dangerous
By being able to modify everything, you are also able to modify the constructor (method/function) so it may be injected and then exploited.
The subject is described analytically here, providing a simple example:
https://web.archive.org/web/20150430062816/https://blog.liftsecurity.io/2015/01/15/the-dangers-of-square-bracket-notation
I've always wondered if there was a way of improving the error message one gets when attempting to use a function that doesn't exist (or that isn't a function). For example:
document.iDontExist()
TypeError: undefined is not a function
I'd like to be able to log something like:
document.iDontExist is not a function
Just to save a few seconds. I realise I have line numbers etc, I'm just wondering whether this is possible.
Is there some property of the TypeError I could use to look up the name that was attempted?
No - not generally.
JavaScript doesn't "send messages" to invoke functions and any expression construct can have the () operator applied .. none of the browser engines try to "read into" the expression to report a more useful message.
A debugger (with break-on-exception) can be useful, but otherwise no - the exceptions will remain general without manual intervention.
Unfortunately not, but if this is an option for you, it could work...
Instead of calling document.iDontExist(), try:
(document.iDontExist || logError("iDontExist undefined")) && document.iDontExist();
This abuses logical operators to only call the function if it exists, and log an error (assuming logError exists!) otherwise.
Hi I'm very new to JS.
Lets say I have an object named test which doesn't have a property missing. But I try to access the same:
test.missing //getting undefined as output
Now I'm trying to access the missing properties ( like this test.missing.404 ) which will give me a TypeError. But my book says we can get rid of this TypeError by like this:
test.missing && test.missing.404
Now my big question is how one can do a && against the undefined type and TypeError type. Couldn't able to guess what Js is doing here.
Thanks in advance.
undefined in js is treated as false and if something has value it is treated as true, so:
//if test.missing is NOT undefined and test.missing.404 is also NOT undefined
if (test.missing && test.missing.404)
First of you should know that JS like many other programming languages uses short circuit technique during comparison. So in this case if the first condition is false then there is no need to check the next condition(s). This is due to the fact that 0 && X will always result 0 .
With that said, test.missing && test.missing.404 can be perceive as "if the test object has missing property and the (test object's) missing property has 404 property" then proceed. Which the JS intepreter will completely ignore the check for 404 property on missing property if the test object has no missing property in the first place.
So the point is the above code is not && comparison of undefined and TypeError but rather check for missing property first and 404 property if first property exists. I hope this makes sense ad explains it well enough.