Search code examples
javascriptnode.jsif-statementerror-handlingundefined

How to fix undefined error handling node.js


const fs = require('fs');
const fileName = './prices.json';
const file = require(fileName);
const price = require('./prices.json');
const fileName = './prices.json';


   if(tmd = message.match(/^!change max (\D+)/)) {
      if(steamID == config.ownerID){
        var kak = tmd[1];
        var sellu = 0;
        sellp = parseInt(message.replace("!change max "+kak,''));
        selli = message.replace("!change max ",'') 
        selli = selli.replace(" "+sellp,'') 
          if (file[selli].max !== undefined){
          file[selli].max = sellp;
          fs.writeFile(fileName, JSON.stringify(file), function writeJSON(err) {
            if (err) return console.log(err);
            client.chatMessage(steamID,"Succesfully changed max of " + selli)
          });
        }else{
        client.chatMessage(steamID,"There was an problem in changing, you might put wrongly name remember about capital letters or\n just do !list and ctrl+c ctrl+v")
        }
    }
  }

UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'max' of undefined

for some reason does not wanna skip the error when its undefiend


Solution

  • You need to check if file[selli] is not undefined first. otherwise u will get an Error inside your if condition.

    Replace

    if (file[selli].max !== undefined){
    

    For

    if (typeof file[selli] !== 'undefined' && typeof file[selli].max !== 'undefined' ) {