Sudden errors in designer, rules failing

I’ve been using a modified version of the TimeOfDay design pattern from the post in these forums (excellent btw - helped me sort a number of design problems and remove duplication).

All of s sudden, Designer is showing little red crosses by these, and the rule fails:

rule "Get time period for right now"
    when
        System started or
        Item SwTest changed to ON
    then
//        val morning = now.withTimeAtStartOfDay.plusHours(6).millis
        val dawn = new DateTime((Dawn_Time.state as DateTimeType).calendar.timeInMillis)
        val sunrise = new DateTime((Sunrise_Time.state as DateTimeType).calendar.timeInMillis)
        val twilight = new DateTime((Twilight_Time.state as DateTimeType).calendar.timeInMillis)
        val evening = new DateTime((Sunset_Time.state as DateTimeType).calendar.timeInMillis)
        val night = now.withTimeAtStartOfDay.plusHours(23).millis

        if(now.isAfter(dawn) && now.isBefore(sunrise))       updateTimeOfDay.apply("Dawn", "Night", true)
        else if(now.isAfter(sunrise) && now.isBefore(twilight)) updateTimeOfDay.apply("Day", "Dawn", true)
        else if(now.isAfter(twilight) && now.isBefore(evening)) updateTimeOfDay.apply("Twilight", "Day", true)
        else if(now.isAfter(evening) && now.isBefore(night))    updateTimeOfDay.apply("Evening", "Twilight", true)
        else                                                    updateTimeOfDay.apply("Night", "Evening", true)
end

Error message:

Error during the execution of startup rule 'Get time period for right now': Cannot cast org.openhab.core.types.UnDefType to org.openhab.core.library.types.DateTimeType

Cheers
James

This error occurs because one of your items is uninitialized when the rule is fired. I think, you have to catch the error by using an if-clause:

if(Dawm_Time.state instanceof DateTimeType)
    val dawn = new DateTime((Dawn_Time.state as DateTimeType).calendar.timeInMillis)

for each new DateTime()…

Or set up persistence so when OH restarts Items get populated with their most recently saved values.