Reference error - null object
-
In Home Assistant I have an integration that if I add entities to it, I will get the following error in MSR as certain entity values I'm using in expressions are null for a moment. This is more or less cosmetic issue and happens very rarely as I rarely modify that integration on the hass side.
And the expression is
Could I "wrap" hass-entity shown above somewhat differently to prevent this error from happening? Using build 24302.
-
@therealdb thanks! I had missed that first "?" -operator
-
T tunnus marked this topic as a question on
-
T tunnus has marked this topic as solved on
-
T tunnus has marked this topic as solved on
-
@tunnus et al, please don't post screen shots of code/expressions or logs. Screen shots often end up displaying at a reduced size that makes them very difficult to read. Just copy-paste the actual text and use a fenced code block.
To the question, as @therealdb said, judicious use of the coalesce operators will generally help here, particularly if you apply local knowledge of the desired outcome. There's another one that's often helpful when working with sources for numeric values that can be occasionally null:
The
?#
operator will take any left side expression and convert it to a number or the value on the right side, sosomeexp ?# -1
would produce -1 if the value ofsomeexp
can't be converted to a number or is null or NaN. In other words, the general formsomexp ?# altval
is shorthand fordo local t=float(someexp), isvalue(t) ? t : altval done
You can use this to produce, for example, an "off scale low" value that wouldn't trip a "greater than" operator on a trigger for a temporary missing value on an entity. This would let you write your expression more tightly as:
round( getEntity( "..." )?.attributes?.current_sensor?.value ?# 0 * getEntity( "..." )?.attributes?.x_hubitat_extra_values?.voltagePhase1 ?# 0, 0 )
Note that the
?#
operator has higher precedence than the math operators (like*
and+
) so you don't need parentheses around the subexpression in this case.That said, if it's specifically zero you're after where there's a null, you may not need to do anything special, because the expression language follows the JavaScript semantics for null in arithmetic: null is treated as zero (e.g.
null * 8 = 0 * 8 = 0
andnull + 8 = 0 + 8 = 8
). So this could be written even shorter as:round( getEntity( "..." )?.attributes?.current_sensor?.value * getEntity( "..." )?.attributes?.x_hubitat_extra_values?.voltagePhase1, 0 )
-
T toggledbits unlocked this topic on
-
T toggledbits locked this topic on