Skip to content

Commit 40bbfec

Browse files
committed
fix: use a decent asyncio handler
1 parent f9739ba commit 40bbfec

File tree

1 file changed

+38
-9
lines changed

1 file changed

+38
-9
lines changed

botbase/botbase.py

+38-9
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from __future__ import annotations
22

3+
import traceback
34
from asyncio import TimeoutError as AsyncTimeoutError
45
from asyncio import wait_for
56
from contextlib import suppress
@@ -220,15 +221,43 @@ def asyncio_handler(self, _, context: dict) -> None:
220221
if context["message"] == "Unclosed client session":
221222
return
222223

223-
log.error(
224-
context["message"]
225-
+ "\n"
226-
+ "\n".join(
227-
f"{k}: {v}"
228-
for k, v in context.items()
229-
if k != "message" and k is not None and v is not None and k != "None"
230-
)
231-
)
224+
message = context.get("message")
225+
if not message:
226+
message = "Unhandled exception in event loop"
227+
228+
exception = context.get("exception")
229+
if exception is not None:
230+
exc_info = (type(exception), exception, exception.__traceback__)
231+
else:
232+
exc_info = False
233+
234+
if (
235+
"source_traceback" not in context
236+
and self.loop._current_handle is not None # pyright: ignore
237+
and self.loop._current_handle._source_traceback # pyright: ignore
238+
):
239+
context[
240+
"handle_traceback"
241+
] = self.loop._current_handle._source_traceback # pyright: ignore
242+
243+
log_lines = [message]
244+
for key in sorted(context):
245+
if key in {"message", "exception"}:
246+
continue
247+
value = context[key]
248+
if key == "source_traceback":
249+
tb = "".join(traceback.format_list(value))
250+
value = "Object created at (most recent call last):\n"
251+
value += tb.rstrip()
252+
elif key == "handle_traceback":
253+
tb = "".join(traceback.format_list(value))
254+
value = "Handle created at (most recent call last):\n"
255+
value += tb.rstrip()
256+
else:
257+
value = repr(value)
258+
log_lines.append(f"{key}: {value}")
259+
260+
log.error("\n".join(log_lines), exc_info=exc_info)
232261

233262
async def start(self, token: str, *, reconnect: bool = True) -> None:
234263
if self.db_enabled:

0 commit comments

Comments
 (0)