简体   繁体   中英

How to fix error Cannot read property 'trim` of undefined

Code:

case `prefix`:
    var prfx = args[3];
    if (!prefix) return msg.reply(`prefix ?`);
    data.prefix = prfx.trim();
    msg.channel.send(`done , my prefix now is : ${prfx}`);
break;

Error:

TypeError: Cannot read property 'trim' of undefined at Client.client.on.msg

In your case prfx is undefined, but you are checking a variable prefix and only return if that one is falsy. You have to check for prfx as well or exclusively.

case `prefix`:
   var prfx = args[3];
   if (!prefix || !prfx) { // Check for prfx as well, since that one could be undefined, maybe !prefix is not even needed or just mispelled
      return msg.reply(`prefix ?`);
   }
   data.prefix = prfx.trim();
   msg.channel.send(`done , my prefix now is : ${prfx}`);
   break;

The args[3] is null or undefined in the args array. you should check it before trim.

 case `prefix`:
   var prfx = args[3];
   if (!prfx) { // prfx is not null or undefined?
     throw 'prfx is null or undefined'; // throw an exception
   }
   data.prefix = prfx.trim();
   msg.channel.send(`done , my prefix now is : ${prfx}`);
   break;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM