From 9f0d1d958676bf7bbc96309f377c932361927929 Mon Sep 17 00:00:00 2001 From: Florian Date: Fri, 1 Mar 2024 18:52:53 +0100 Subject: [PATCH] Improve error handling MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit So the script does not log the db credentials 🙄. --- query_and_submit.py | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/query_and_submit.py b/query_and_submit.py index fbc6806..899d5bc 100644 --- a/query_and_submit.py +++ b/query_and_submit.py @@ -7,6 +7,7 @@ import yaml import urllib.parse + def read_secret_file(key): try: with open(key, "r") as secret_file: @@ -45,16 +46,22 @@ def read_secret_file(key): sql = query["countSql"] condition_keyword = "and" if re.search("where", sql, re.IGNORECASE) else "where" timestamp_col = query["timestampColumn"] - metrics[metric_name] = json.loads( - subprocess.check_output( - [ - "psql", - db_uri, - "-Atc", - f"{sql} {condition_keyword} \"{timestamp_col}\" between '{interval_start}' and '{interval_end}'", - ] + + try: + metrics[metric_name] = json.loads( + subprocess.check_output( + [ + "psql", + db_uri, + "-Atc", + f"{sql} {condition_keyword} \"{timestamp_col}\" between '{interval_start}' and '{interval_end}'", + ] + ) ) - ) + except subprocess.CalledProcessError as e: + print(f"Command execution failed with exit status {e.returncode}.") + except Exception as e: + print("An error occurred while executing the script") response = requests.post( url=config["endpoint"],