From 4f7eb12dc3508e270daff924f1b22de0e0aed0bb Mon Sep 17 00:00:00 2001 From: Derpitron Date: Tue, 28 Nov 2023 22:56:16 +0530 Subject: [PATCH] Robustly and Pythonically implemented error handling --- main.py | 5 +++-- src/backend.py | 9 +++++---- src/lib/exceptions.py | 5 +++++ 3 files changed, 13 insertions(+), 6 deletions(-) create mode 100644 src/lib/exceptions.py diff --git a/main.py b/main.py index 4b138b5..7e73b54 100644 --- a/main.py +++ b/main.py @@ -9,6 +9,7 @@ from src.lib.textcolor import color from src.backend import bootstrap_browser, bootstrap_login_page +from src.lib.exceptions import UserCausedHalt def load_configuration(configuration_file_path='user/cfg.yml') -> dict: """ @@ -74,7 +75,7 @@ def userFacing(configuration: dict): if __name__ == '__main__': try: userFacing(load_configuration()) - except KeyboardInterrupt: + except UserCausedHalt: # Exit procedure taken from: https://stackoverflow.com/a/21144662 - logger.info('Halting Program on KeyboardInterrupt') + logger.info('User halted the program!') sys.exit(130) diff --git a/src/backend.py b/src/backend.py index 47da792..7b16745 100644 --- a/src/backend.py +++ b/src/backend.py @@ -2,8 +2,10 @@ import os import time import secrets + from src.lib.codegen import generate_random_code from src.lib.textcolor import color +from src.lib.exceptions import UserCausedHalt from loguru import logger sensitive_debug = logger.level(name="SENSITIVE_DEBUG", no=15, color="") @@ -247,9 +249,8 @@ def code_entry( print_session_statistics('invalid_session_ticket', session_statistics) except KeyboardInterrupt: session_statistics['elapsedTime'] = time.time() - start_time - print_session_statistics('closed_by_user_keyboard_interrupt', session_statistics) - raise KeyboardInterrupt - + print_session_statistics('closed_by_user', session_statistics) + raise UserCausedHalt def print_session_statistics( halt_reason: str, @@ -267,7 +268,7 @@ def print_session_statistics( halt_reasons = { 'invalid_session_ticket': 'Invalid session ticket', 'invalid_password_reset_token': 'Invalid password reset token', - 'closed_by_user_keyboard_interrupt': 'Halted by user (KeyboardInterrupt)', + 'closed_by_user': 'Halted by user', 'password_reset_required': f"We need to reset the password!\n"\ f"Running 'reset program mode'!\n"\ diff --git a/src/lib/exceptions.py b/src/lib/exceptions.py new file mode 100644 index 0000000..6340f66 --- /dev/null +++ b/src/lib/exceptions.py @@ -0,0 +1,5 @@ +class UserCausedHalt(Exception): + """ + Raised when user manually quit the application + """ + pass \ No newline at end of file