feat: Add error handling to shipment processing loops

The previous code did not handle errors while processing shipments, which could lead to unexpected behavior. This commit adds error handling to the shipment processing loops to log and handle various types of exceptions. Now, exceptions such as database timeouts and keyboard interrupts are caught and logged appropriately.
This commit is contained in:
Kumi 2023-09-06 08:13:37 +02:00
parent f2ca2e0748
commit 22d2c06f60
Signed by: kumi
GPG key ID: ECBCC9082395383F

View file

@ -3,6 +3,7 @@ import subprocess
import time
import importlib
import asyncio
import sqlalchemy.exc
from pathlib import Path
from typing import Optional, Tuple, Never
@ -160,10 +161,21 @@ class Tracker:
logging.debug("Starting loop")
while True:
for shipment in self.db.get_shipments():
self.process_shipment(shipment)
try:
for shipment in self.db.get_shipments():
self.process_shipment(shipment)
time.sleep(self.loop_interval)
time.sleep(self.loop_interval)
except sqlalchemy.exc.TimeoutError:
logging.warning("Database timeout while processing shipments")
except KeyboardInterrupt:
logging.info("Keyboard interrupt, exiting")
sys.exit(0)
except Exception as e:
logging.exception(f"Unknown error in loop: {e}")
async def start_loop_async(self) -> Never:
logging.debug("Starting loop")
@ -181,9 +193,20 @@ class Tracker:
try:
await asyncio.gather(*tasks)
except asyncio.TimeoutError:
logging.warning("Timeout while processing shipments")
except sqlalchemy.exc.TimeoutError:
logging.warning("Database timeout while processing shipments")
except KeyboardInterrupt:
logging.info("Keyboard interrupt, exiting")
sys.exit(0)
except Exception as e:
logging.exception(f"Unknown error in loop: {e}")
await asyncio.sleep(self.loop_interval)
def _pre_start(self, config: Optional[PathLike] = None):