'aiogram.utils.exceptions.NetworkError breaks while loop of telegram bot

There is a telegram bot on aiogram.

# ... missing code...

async def current_info(message: types.Message, state: FSMContext):
    current_data = {}
    while True:
        local_file = open(json_file, 'r')
        local_data = local_file.get('data')
        if local_data and local_data != current_data:
            current_data = local_data
            await message.answer(str(current_data))
        await asyncio.sleep(10)

# ... missing code...

def register_handlers(dp: Dispatcher):
    # ... missing code...
    # InfoState.ok - successful authorization status
    dp.register_message_handler(current_info, lambda message: message.text == "Start watching                 
                                current updates", state=InfoState.ok)

# ... missing code...

Above presented a simplified structure. That is, there is a coroutine that accepts the command "Start watching current updates" 1 time - after which it starts endless requests to "json_file" for something new and after sending it to the user.

Everything works well except for one thing. When it jumps:

aiogram.utils.exceptions.NetworkError

bot does not crash its work - it continues to function and respond to direct user requests: "command - request". But the while True loop crashes. And the worst thing is that I can't catch this error - and, for example, cause a message to the user, where he will restart the loop with the button "Start watching current updates".

The desired result for me is catching this error to further restart the while True loop, but not the entire bot.

Attempts to wrap try except with my if __name__ == '__main__': asyncio.run(main()) obviously didn't work.

I apologize in advance for the stupidity, and thank you very much for any of your answers and hints!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source