Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: better exception handling #133

Merged
merged 6 commits into from
Aug 31, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 24 additions & 4 deletions python/src/uagents/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import functools
from typing import Dict, List, Optional, Set, Union, Type, Tuple, Any, Coroutine
import uuid
from pydantic import ValidationError
import requests

from cosmpy.aerial.wallet import LocalWallet, PrivateKey
Expand Down Expand Up @@ -386,11 +387,21 @@ async def handle_message(
async def _startup(self):
await self._registration_loop()
for handler in self._on_startup:
await handler(self._ctx)
try:
await handler(self._ctx)
except OSError as ex:
self._logger.exception(f"OS Error in startup handler: {ex}")
except RuntimeError as ex:
self._logger.exception(f"Runtime Error in startup handler: {ex}")

async def _shutdown(self):
for handler in self._on_shutdown:
await handler(self._ctx)
try:
await handler(self._ctx)
except OSError as ex:
self._logger.exception(f"OS Error in shutdown handler: {ex}")
except RuntimeError as ex:
self._logger.exception(f"Runtime Error in shutdown handler: {ex}")

def setup(self):
# register the internal agent protocol
Expand Down Expand Up @@ -436,7 +447,11 @@ async def _process_message_queue(self):
continue

# parse the received message
recovered = model_class.parse_raw(message)
try:
recovered = model_class.parse_raw(message)
except ValidationError as ex:
self._logger.warning(f"Unable to parse message: {ex}")
continue

context = Context(
self._identity.address,
Expand Down Expand Up @@ -475,7 +490,12 @@ async def _process_message_queue(self):
continue

if handler is not None:
await handler(context, sender, recovered)
try:
await handler(context, sender, recovered)
except OSError as ex:
self._logger.exception(f"OS Error in message handler: {ex}")
except RuntimeError as ex:
self._logger.exception(f"Runtime Error in message handler: {ex}")


class Bureau:
Expand Down
17 changes: 12 additions & 5 deletions python/src/uagents/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,11 +242,18 @@ async def send_raw(
env.encode_payload(json_message)
env.sign(self._identity)

async with aiohttp.ClientSession() as session:
async with session.post(
endpoint, headers={"content-type": "application/json"}, data=env.json()
) as resp:
success = resp.status == 200
try:
async with aiohttp.ClientSession() as session:
async with session.post(
endpoint,
headers={"content-type": "application/json"},
data=env.json(),
) as resp:
success = resp.status == 200
except aiohttp.ClientConnectorError as ex:
self._logger.exception(f"Failed to connect to {endpoint}: {ex}")
except Exception as ex:
self._logger.exception(f"Failed to send message to {destination}: {ex}")

if not success:
self._logger.exception(
Expand Down
37 changes: 24 additions & 13 deletions python/src/uagents/mailbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,17 +84,26 @@ async def _handle_envelope(self, payload: dict):
async def process_deletion_queue(self):
async with aiohttp.ClientSession() as session:
while True:
env_payload = await self._envelopes_to_delete.get()
env_url = f"{self.http_prefix}://{self.base_url}/v1/mailbox/{env_payload['uuid']}"
self._logger.debug(f"Deleting message: {env_payload}")
async with session.delete(
env_url,
headers={"Authorization": f"token {self._access_token}"},
) as resp:
if resp.status != 200:
self._logger.exception(
f"Failed to delete envelope from inbox: {(await resp.text())}"
)
try:
env = await self._envelopes_to_delete.get()
env_url = (
f"{self.http_prefix}://{self.base_url}/v1/mailbox/{env['uuid']}"
)
self._logger.debug(f"Deleting message: {env}")
async with session.delete(
env_url,
headers={"Authorization": f"token {self._access_token}"},
) as resp:
if resp.status != 200:
self._logger.exception(
f"Failed to delete envelope from inbox: {(await resp.text())}"
)
except ClientConnectorError as ex:
self._logger.warning(f"Failed to connect to mailbox server: {ex}")
except Exception as ex:
self._logger.exception(
f"Got exception while processing deletion queue: {ex}"
)

async def _poll_server(self):
async with aiohttp.ClientSession() as session:
Expand Down Expand Up @@ -133,10 +142,12 @@ async def _open_websocket_connection(self):
await self._handle_envelope(msg["payload"])

except websockets.exceptions.ConnectionClosedError:
pass
self._logger.warning("Mailbox connection closed")
self._access_token = None

except ConnectionRefusedError:
pass
self._logger.warning("Mailbox connection refused")
self._access_token = None

async def _get_access_token(self):
async with aiohttp.ClientSession() as session:
Expand Down
Loading