How to treat missing data in the rule

In the rule I’m reading a historic data :

val read = Spotreba_FVE_BAT_dnes.historicState(actual_day.minusDays(i).minusSeconds(2)).state as Number

but one day I have a problem, that data in correct time 23:59:58 are missing and for debug it’s error :

2024-06-19 23:26:38.659 [ERROR] [internal.handler.ScriptActionHandler] - Script execution of rule with UID '3fae87c668' failed: cannot invoke method public abstract org.openhab.core.types.State org.openhab.core.persistence.HistoricItem.getState() on null

how to treat a missing data which returns a null ?
Because I’m looking for maximum value for each day (that’s why I’looking for midnight value), maybe other function like maximumSince will work ?

As always in OH, there are several ways of doing this, using maximumSince is certainly one of them. To give more suggestions we would need a bit of context though, e.g., does the value of the item always increase? Is it reset at midnight or increases continuously? What do you use the value for? Is the timing of the usage important (must the rule be executed strictly after midnight)?

Value increase every day and during midnight is reset :

problem is, that I did some changes in the persistance configuration and there a day where part of data is missing :

Rule I’m using for complete consumption calculation for actual month. So I’m making sum of values from each day at 23:59:58 :

var Number cons_fve_bat_this_month = 0
for(var i=0; i<(zdt.getDayOfMonth-1); i++){
val read = cons_FVE_BAT_today.historicState(actual_day.minusDays(i).minusSeconds(2)).state as Number
cons_fve_bat_this_month = cons_fve_bat_this_month + read 
}
cons_fve_bat_this_month = cons_fve_bat_this_month + cons_fve_bat_from_the_morning
postUpdate(cons_FVE_BAT_actual_month, cons_fve_bat_this_month)   

So you run the rule each day, and want to calculate the cumulative consumption for the current month, correct? Then maximumSince cannot be used, since that would only work for the very last day. Since OH 3.4 there is a maximumBetween(ZonedDateTime start, ZonedDateTime end) method that could be used instead though. Something like (NOT TESTED):

val endDate = ZonedDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0)
var Number cons_fve_bat_this_month = 0
for(var i=0; i<(endDate.getDayOfMonth - 1); i++){
val read = cons_FVE_BAT_today.maximumBetween(endDate.minusDays(i + 1), endDate.minusDays(i)).state as Number
cons_fve_bat_this_month = cons_fve_bat_this_month + read 
}
cons_fve_bat_this_month = cons_fve_bat_this_month + cons_fve_bat_from_the_morning
postUpdate(cons_FVE_BAT_actual_month, cons_fve_bat_this_month)   

Forgot to ask, but is the item reset by a rule scheduled at midnight, or is it done by an external device/service that the information comes from? That could also have an effect on what approach would be best.

It’s done by external device.