Inconsistent error when using msg.payload.toLowerCase()

I’m using an “Edit Function” node to test for various weather conditions. Information input to the node is not case (upper/lower) consistent so I’m using the toLowerCase() function to convert the incoming payload to lower case before testing it. The node outputs what I expect when an Inject nodes is used to inject a weather condition. Let me explain further. If “Snowy” or “snowy” is injected, the node outputs the payload that code within the node selects. If I allow the flow to work on it’s own, when the state node passes on current weather conditions, I sometimes see an error;

“TypeError: msg.payload.toLowerCase is not a function”

The code in the “Edit Function” node is as follows;

const globalHomeAssistant = global.get('homeassistant');
var weather_condition = msg.payload.toLowerCase();

if (weather_condition == "snowy" || weather_condition == "snow" || weather_condition == "heavy snow" || weather_condition == "heavy flurries" || weather_condition == "blowing snow" || weather_condition == "drifting snow" ) {
    msg.payload = "turn_on";
    return [msg,null];
}else{
    if (weather_condition == "clear") {
        msg.payload = "STOP";
        return [null,msg];
    }
}
return [null,null]

What is causing the error to occur?

Msg.payload might not be a string then.

Hmm! I’m not sure that would be the case. Payload is passed from an “events: state” node. The state type for that node is set to “string”. Doesn’t that mean the payload would be output as a string?

Take a look at the “String” node. You can use it to first convert any input toString, followed by a toLowerCase.

@mightybosstone , Thanks for pointing this node out. As a result of looking at how it works, I realized the issue really stemmed from an incorrectly configured State Node. Rather than passing the “state” of the entity, it was passing all events related to the entity. This meant payload messages contained information that, in some cases were numerical which was causing the toLowerCase() function to fail.

a string variable can also contain the value null.

I didn’t think of that! Good point, thanks.

I’ve used the following in a function node to check for a missing (NaN) value. You likely could also use it to check for a missing (NA) or empty (NULL) value.

if(isNaN(msg.payload)) {
  return null; //halt flow
}
return msg;

Always better to be safe than sorry. I adjust code accordingly. Thanks