From ee26f3e913b210fb248897ba17d64a016c21e313 Mon Sep 17 00:00:00 2001 From: Oleg Silkin Date: Sat, 20 Jul 2019 09:10:14 -0400 Subject: [PATCH] Better Logging + Error handling --- src/handles.py | 12 ++---------- src/misc.py | 11 +++++++++++ 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/src/handles.py b/src/handles.py index ca3677e..f981f69 100644 --- a/src/handles.py +++ b/src/handles.py @@ -14,6 +14,7 @@ from src.database import obtain_connection from src.database import delete_comment_by_id from src.writes import create_comment_or_error from src.misc import is_authentic_delete_signal +from src.misc import make_error logger = logging.getLogger(__name__) @@ -101,7 +102,7 @@ async def process_json(app, body: dict) -> dict: else: response['error'] = make_error('INTERNAL', err) else: - response['error'] = ERRORS['METHOD_NOT_FOUND'] + response['error'] = make_error('METHOD_NOT_FOUND') return response @@ -117,15 +118,6 @@ async def api_endpoint(request: web.Request): ) else: return web.json_response(await process_json(request.app, body)) - else: - logger.warning('Got invalid request from %s: %s', request.remote, body) - return web.json_response({'error': ERRORS['INVALID_REQUEST']}) - except json.decoder.JSONDecodeError as jde: - logger.exception('Received malformed JSON from %s: %s', request.remote, jde.msg) - logger.debug('Request headers: %s', request.headers) - return web.json_response({ - 'error': ERRORS['PARSE_ERROR'] - }) except Exception as e: logger.exception(f'Exception raised by request from {request.remote}: {e}') logger.debug(f'Request headers: {request.headers}') diff --git a/src/misc.py b/src/misc.py index 31ffa8d..1683c68 100644 --- a/src/misc.py +++ b/src/misc.py @@ -31,6 +31,17 @@ ERRORS = { } +def make_error(error, exc: Exception = None) -> dict: + body = ERRORS[error] if error in ERRORS else ERRORS['INTERNAL'] + try: + if exc: + body.update({ + type(exc).__name__: str(exc) + }) + finally: + return body + + def channel_matches_pattern(channel_id: str, channel_name: str): assert channel_id and channel_name assert type(channel_id) is str and type(channel_name) is str