Best way to handle no results or errors in an api call in an automation

Hello, I have an automation and although everything works well, I would like it to be “cleaner” and if the calls to the api do not give any result, I would like to handle it in the best possible way. At the moment when the call to the api does not give any result, the automation does not continue and the input_text and the sensor are not updated or show any error, both keep the last value. and it’s ok for me but I don’t think it is the right way to do it.

The automation is this

alias: Caratula Juego Xbox
description: Muestra la caratula del juego de xbox que se esté jugando en este momento.
  - platform: state
      - sensor.d13g0_m0nt3s_status
  - condition: state
    entity_id: binary_sensor.d13g0_m0nt3s_in_game
    state: "on"
  - service: rest_command.trigger_idjuego_service
    data: {}
    response_variable: idjuego
  - service: input_text.set_value
      entity_id: input_text.idjuego
      value: "{{idjuego['content']['games'][0].game_id}}"
  - delay:
      hours: 0
      minutes: 0
      seconds: 5
      milliseconds: 0
  - service: rest_command.trigger_caratula_service
    data: {}
    response_variable: caratula
  - service: input_text.set_value
      entity_id: input_text.caratula
      value: "{{caratula['content']['cover_groups'][0].covers[0].image}}"

And the api returns when no results found :


and when an error occur:

  "code": 401,
  "error": "Authorization required",
  "message": "You must have an API key to use this resource."

with a different code according the kind the error.

How should I handle not receiving results or a possible error?

Thanks in advance

Something like this:

  - service: input_text.set_value
      entity_id: input_text.idjuego
      value: >
        {% if code is defined %}
          {{ code ~ ": " ~ error ~ ". " ~ message }}
        {% elif games == [] %}
          No game available.
        {% else %}
          {{ idjuego['content']['games'][0].game_id }}
        {% endif %}
1 Like

Thanks! I will try that and let you know :smiling_face:

I tried your code and it seems its bypassing de elif games == . I`m getting this error:

Error rendering data template: UndefinedError: list object has no element 0

If i put the full idjuego variable into the input text and i got:

{'content': {'games': []}, 'status': 200}

it seems it is ignoring the games ==

A silly question. i will try to splain the best i can, english it is not my first languege. How knows the conditional where to look?. i know the variable idjuego is defined previously but you never told the if else where to look in the code. i.m new to yaml and jinja2 sorry

thanks in advance.

fixed and working great with:

    {% if  idjuego['content']['games'] == []   %}
      No game available.
    {% elif idjuego['content']['code'] is defined %}
     Ha ocurrido un error
    {% else %}
      {{ idjuego['content']['games'][0].game_id }}
    {% endif %}