Skip to content

Commit 6ff788f

Browse files
committed
Add exception handling for database functions
1 parent 2472cac commit 6ff788f

File tree

2 files changed

+19
-3
lines changed

2 files changed

+19
-3
lines changed

similarity-service-cosine/cosine_impl/cosine_impl_controller.py

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import connexion
22
import numpy as np
3+
from connexion import problem
4+
from flask import jsonify, Flask
35
from matchms import Spectrum, calculate_scores
46
from matchms.similarity import CosineGreedy
57

@@ -17,6 +19,7 @@
1719
DB_HOST = os.environ.get('DB_HOST', "localhost")
1820
DB_NAME = os.environ.get('DB_NAME', "massbank3")
1921

22+
app = Flask(__name__)
2023

2124
def similarity_post(similarity_calculation): # noqa: E501
2225
"""Create a new similarity calculation.
@@ -31,8 +34,16 @@ def similarity_post(similarity_calculation): # noqa: E501
3134
if connexion.request.is_json:
3235
request = SimilarityCalculation.from_dict(similarity_calculation)
3336

34-
reference_spectra = ReferenceSpectra(psycopg.connect(f"postgresql://{DB_NAME}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_NAME}"))
35-
reference_spectra.load_spectra()
37+
try:
38+
reference_spectra = ReferenceSpectra(
39+
psycopg.connect(f"postgresql://{DB_NAME}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_NAME}"))
40+
reference_spectra.load_spectra()
41+
except psycopg.DatabaseError as e:
42+
return problem(
43+
title="Database Error",
44+
detail=str(e),
45+
status=500,
46+
)
3647

3748
mz = []
3849
intensities = []
@@ -70,3 +81,9 @@ def version_get(): # noqa: E501
7081
:rtype: Union[str, Tuple[str, int], Tuple[str, int, Dict[str, str]]
7182
"""
7283
return 'cosine similarity 1.0.0'
84+
85+
86+
def handle_psycopg_database_error(error):
87+
response = jsonify(error.to_dict())
88+
response.status_code = error.status_code
89+
return response

similarity-service-cosine/cosine_impl/db.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ def __init__(self, connection):
1313
"""initialize the class with a database connection"""
1414
self.connection = connection
1515

16-
@property
1716
def load_spectra(self):
1817
"""load all spectra from the database if the metadata indicates newer data and stores them"""
1918
with self.connection.cursor() as cur:

0 commit comments

Comments
 (0)