From d90c9a072cb61421aaab7328a8b95e01441ca548 Mon Sep 17 00:00:00 2001 From: Richard Chien Date: Tue, 25 Dec 2018 20:40:36 +0800 Subject: [PATCH] Improve exception handling --- none/command.py | 4 +++- none/natural_language.py | 16 ++++++++++++---- none/notice_request.py | 6 +++++- 3 files changed, 20 insertions(+), 6 deletions(-) diff --git a/none/command.py b/none/command.py index a0d3fd50..b6067dea 100644 --- a/none/command.py +++ b/none/command.py @@ -400,7 +400,7 @@ def parse_command(bot: NoneBot, return None, None logger.debug(f'Matched command start: ' - f'{matched_start}{"(space)" if not matched_start else ""}') + f'{matched_start}{"(empty)" if not matched_start else ""}') full_command = cmd_string[len(matched_start):].lstrip() if not full_command: @@ -565,6 +565,8 @@ async def _real_run_command(session: CommandSession, SwitchException) as e: raise e except Exception as e: + logger.error(f'An exception occurred while ' + f'running command {session.cmd.name}:') logger.exception(e) handled = True raise _FinishException(handled) diff --git a/none/natural_language.py b/none/natural_language.py index 6d41f45b..a93ef61e 100644 --- a/none/natural_language.py +++ b/none/natural_language.py @@ -109,7 +109,7 @@ async def handle_natural_language(bot: NoneBot, ctx: Context_T) -> bool: # at the same time some plugins may want to handle it msg_text_length = len(session.msg_text) - coros = [] + futures = [] for p in _nl_processors: if not p.allow_empty_message and not session.msg: # don't allow empty msg, but it is one, so skip to next @@ -132,11 +132,19 @@ async def handle_natural_language(bot: NoneBot, ctx: Context_T) -> bool: should_run = False if should_run: - coros.append(p.func(session)) + futures.append(asyncio.ensure_future(p.func(session))) - if coros: + if futures: # wait for possible results, and sort them by confidence - results = sorted(filter(lambda r: r, await asyncio.gather(*coros)), + results = [] + for fut in futures: + try: + results.append(await fut) + except Exception as e: + logger.error('An exception occurred while running ' + 'some natural language processor:') + logger.exception(e) + results = sorted(filter(lambda r: r, results), key=lambda r: r.confidence, reverse=True) logger.debug(f'NLP results: {results}') if results and results[0].confidence >= 60.0: diff --git a/none/notice_request.py b/none/notice_request.py index 0c0ca371..a765496b 100644 --- a/none/notice_request.py +++ b/none/notice_request.py @@ -94,7 +94,11 @@ async def handle_notice_or_request(bot: NoneBot, ctx: Context_T) -> None: session = RequestSession(bot, ctx) logger.debug(f'Emitting event: {event}') - await _bus.emit(event, session) + try: + await _bus.emit(event, session) + except Exception as e: + logger.error(f'An exception occurred while handling event {event}:') + logger.exception(e) def _log_notice(ctx: Context_T) -> None: