Changing template query makes ha crash

I use auto-entities and I use this template

  template: >-
    {{ states.sensor  | selectattr('attributes.device_class', '==',
    'temperature') | selectattr('last_updated', '<=', now() -
    timedelta(hours=18)) | map(attribute='entity_id') | list}}

now I also want to find stale humidity sensors,
So I modified this to:

  template: >-
    {{ states.sensor  | selectattr('attributes.device_class', 'search',
    '(temperature|humidity)') | selectattr('last_updated', '<=', now() -
    timedelta(hours=18)) | map(attribute='entity_id') | list}}

but for some reason this makes HA crash/loose connection

Some entities won’t have adevice_class defined. The equality comparison can handle that but the search test can’t.

You should first select the entities that have a device_class defined. You should do this for both templates, even though it’s not causing errors in the first template.

I also changed the test from search to in because the device class should be exactly equal to one of those options, so no need to search.

template: >-
  {{ states.sensor
    | selectattr('attributes.device_class', 'defined')
    | selectattr('attributes.device_class', 'in', ['temperature', 'humidity'])
    | selectattr('last_updated', '<=', now() - timedelta(hours=18))
    | map(attribute='entity_id')
    | list }}