how can I fix Cannot read property 'error' of undefined - javascript

I fetch Data and want to output the data. It Works but I also want to make a error handling.
Like:
const func = async data => {
try {
const res = await fetch('MY_URL);
const out = await res.json();
if(out) {
const name = out.result.name;
if(out.result.error) {
console.log('ERROR');
}
}
} catch(e) {
console.log(e);
}
};
Why I get this message?
Cannot read property 'error' of undefined
Ok, I dont have an object with error, but I want to say If there is an error object, then I want to show anything else.
How I fix it?
EDIT:
// Error Handling Statuscode
if (out.result[0].statuscode.error) {
allCircle[0].innerHTML = errorIcon;
domainInfo[0].innerText = out.result[0].statuscode.error;
}
I dont have statuscode.error. But If an Error in my system happens, then I get the property error. So how can I say If error exists? Because error property doesnt always exists.

You could try something like:
if(out.result && out.result.error) {
console.log('ERROR');
}
That way you would shortcut the evaluation of the error property if there is no result property in the first place.

Why I get this message?
Cannot read property 'error' of undefined
this because your out object does not have result parameter every time, and returns undefined at that time so you cant access to out.result.error because out.result is undefined
Solution
if(out?.result?.error) {
console.log('ERROR');
}

Related

Uncaught TypeError: Cannot read property 'match' of undefined in React

I'm trying to make a simply submit form. I believe my json in mailformat is correct. Using the json in mailformat, I'm trying to check if the email that has been submitted is valid. However for some reason, react doesn't appear to be recognizing the match() method. I get an error stating "Cannot read property 'match' of undefined." My guess for a fix is something involving asynchronous programming but I am not skilled enough to come up with a fix. I'm using react hooks and state.
function Form({submit, setSubmit, text, setText}) {
let emailArray = [];
//handlers. Need for submit button and input for text
const setTextHandler = (e) => {
// console.log(e.target.value)
setText(e.target.value);
};
const setSubmitHandler = (e) => {
let mailformat = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
e.preventDefault();
setSubmit(text);
console.log(text)
if(text.value.match(mailformat)) {
console.log("it works")
emailArray.push(text);
return true
} else if (!text.value.match(mailformat)) {
console.log("FAIL");
return false
}
console.log(emailArray[0])
console.log(emailArray)
setText("");
}
Based on your last line and your setTextHandler, both setText functions are setting the text value to a string so just changing this lines would do the trick:
if(text.match(mailformat)) {
// your code
} else if (!text.match(mailformat)) {
// your code
}

TypeError: Cannot read property 'bulkDelete' of undefined

I don't know what the problem is, I always get an error message when I execute the command: TypeError: Cannot read property 'bulkDelete' of undefined
I'm working with discord.js
My Code:
module.exports = {
name: 'clear',
async execute(message, args) {
if (!args[0]) return message.channel.send("-")
if (isNaN(args[0])) return message.channel.send("-")
if (args[0] > 100) return message.channel.send("-")
if (args[0] < 1) return message.channel.send
await message.channel.messages.fetch({Limit: args[0]}).then(message =>{
message.channel.bulkDelete(messages);
});
}
}
Regardless of what bulkDelete is try to check if it exists like:
if (message?.channel?.bulkDelete) {
message.channel.bulkDelete();
}
So, assuming that this is the Discord API that you're working with:
channel.messages is a MessageManager
When you call fetch with anything other than a message ID, you're going to get a Collection back, rather than a single message.
Thus, what you call message, should really be called messages and you should interact with it as a set of messages, rather than a single one.

Undefined error getting in javascript (React Native)

I am storing particular key value in Database. But, While fetching the key value, getting undefined error.
await DbHandler.fetch(codeStatus)
.then((result) => {
const codeEnabledObj = result[0];
console.log('codeEnabledObj', codeEnabledObj);
let codeEnabled = false;
if (codeEnabledObj && codeEnabledObj.length > 0) { // this code not executing at all.
codeEnabled = codeEnabledObj[0].isEnabled;
}
console.log('codeEnabled', codeEnabled); // getting false always
console.log('codeEnabledObj.length[0]', codeEnabledObj.length); // undefined
})
.catch((error) => {
});
The issue is, It's not going inside if condition and throwing error like undefined.
But, If we print the response from db fetch
'codeEnabledObj', { type: 'codeStatus', isEnabled: true } // This is my response
Any suggestions?
Objects don't have length property like an array.
codeEnabledObj.length is wrong
use this,
Object.keys(codeEnabledObj).length
EDIT :
codeEnabledObj[0].isEnabled should be only codeEnabledObj.isEnabled
There is no property length in the codeEnabledObj , Moreover its not an Array.. so modifying the condition would work, where isEmpty could be a function used from
node package as underscore
if (isEmpty(codeEnabledObj)) { // ... }
and
codeEnabledObj.isEnabled
Thanks.

React native cannot read property '0' of undefine

I'm new with ReactJS and today I have encountered a few problems.
I am currently using Redux to store my data and I was able to retrieve all the data from the props.
Ie.
const { recipe, loadingRDetail } = this.props;
console.log(recipe.macros);
recipe macros will show me 5 values in array.
Array Image Console Log
But when I tried to accessed to the array, It will throw me an error "Cannot read property '0' of undefined".
I have tried
console.log(recipe.macros[0])
and
const {macros} = recipe;
macros.map((i) => {
....
}...
I have no luck with both of these
This is the error I get
Red Warning error
Actually, it's just because your macros data is asynchronously loaded so you have to add a test to check if it's loaded.
You can try this:
const {macros} = recipe;
if (macros && macros.length) {
macros.map((i) => {
....
}...
}
Or if you already are in your Render method you can just try this :
const {macros} = recipe;
return (
{
macros && macros.length && /* It will check if macros has elements inside */
macros.map((i) => {
....
}...
}
}
)

Node.js Error Handling -- how to deal with undefined values causing errors

Take this URL for instance: https://api.eveonline.com/eve/CharacterID.xml.aspx?names=Khan
Using xml2js node.js module you may parse that XML, although it does not look pretty:
var CharacterID = response.eveapi.result[0].rowset[0].row[0].$.characterID;
The app crashed after 2 weeks of running, all because rowset[0] was undefined. Prior to that it crashed because eveapi was not defined. Seriously, does my if-else has to be like this just to prevent server from crashing due to stupid undefined object errors?
if (!response.eveapi ||
!response.eveapi.result[0] ||
!response.eveapi.result[0].rowset[0] ||
!response.eveapi.result[0].rowset[0].row[0]) {
return res.send(500, "Error");
Besides the obvious if (err) return res.send(500, "Error"); error handling where applicable, what is the general practice for undefined errors?
I wrote a library for this kind of thing, called dotty (https://github.com/deoxxa/dotty).
In your case, you could do this:
var dotty = require("dotty");
var CharacterID = dotty.get(response, "eveapi.result.0.rowset.0.row.0.$.characterID");
In the case of the path not being resolvable, it'll just return undefined.
As you've discovered, undefined is not itself an error, but using undefined as an array/object is an error.
x = {'a': { 'b': { 'c': { 'd': [1,2,3,4,5]} } } } ;
try { j = x.a.b.c.e[3] } catch(e) { console.log(e); }
prints
[TypeError: Cannot read property '3' of undefined]
This suggests to me that try/catch can be used with your code to return an error code, and if desired, an error text (or just stick the error text in console.log, a database or local file).
In your case, that could look like:
var CharacterID; // can't define it yet
try {
CharacterID = response.eveapi.result[0].rowset[0].row[0].$.characterID;
} catch(e) {
// send description on the line with error
return res.send(500, "Error: NodeJS assigning CharacterID: "+e);
// return res.send(500, "error"); use this one if you dont want to reveal reason for errors
}
// code here can assume CharacterID evaluated. It might still be undefined, though.
Maybe this function helps?
function tryPath(obj, path) {
path = path.split(/[.,]/);
while (path.length && obj) {
obj = obj[path.shift()];
}
return obj || null;
}
For your code you'd use:
if (tryPath(response,'eveapi.result.0.rows.0.row.0') === null) {
return res.send(500, "Error");
}
jsFiddle example
jsFiddle same example, but as extension to Object.prototype

Categories