Skip to content

Commit 5cc2000

Browse files
committed
exceptions, db: catch all sqlite exceptions
Create a new dedicated exception class (DBException) which will be raised instead of sqlite3.Error (provide abstraction).
1 parent bfb1089 commit 5cc2000

File tree

2 files changed

+27
-11
lines changed

2 files changed

+27
-11
lines changed

src/numbat/db.py

Lines changed: 23 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919

2020
import sqlite3
2121

22-
from .exceptions import NumbatException
22+
from .exceptions import DBException, NumbatException
2323
from .types import (
2424
ComponentAccess,
2525
ComponentAccessType,
@@ -60,7 +60,11 @@ def connect(path: str) -> sqlite3.Connection:
6060
:return: A connection handle that can be used for future
6161
operation on the database
6262
"""
63-
return sqlite3.connect(path)
63+
try:
64+
res = sqlite3.connect(path)
65+
except sqlite3.Error as e:
66+
raise DBException(f"Error while connecting to DB: {e}") from e
67+
return res
6468

6569
@staticmethod
6670
def exec(
@@ -75,11 +79,14 @@ def exec(
7579
:return: The id of the last modified row (useful in case insertion)
7680
"""
7781
if not database:
78-
raise Exception("Invalid database handle")
79-
80-
cur = database.cursor()
81-
cur.execute(request, parameters)
82-
cur.close()
82+
raise DBException("Invalid database handle")
83+
84+
try:
85+
cur = database.cursor()
86+
cur.execute(request, parameters)
87+
cur.close()
88+
except sqlite3.Error as e:
89+
raise DBException(f"Error while excuting request to DB: {e}") from e
8390
return cur.lastrowid
8491

8592
@staticmethod
@@ -97,10 +104,15 @@ def fetch(
97104
if not database:
98105
raise Exception("Invalid database handle")
99106

100-
cur = database.cursor()
101-
cur.execute(request, parameters)
102-
result = cur.fetchall()
103-
cur.close()
107+
try:
108+
cur = database.cursor()
109+
cur.execute(request, parameters)
110+
result = cur.fetchall()
111+
cur.close()
112+
except sqlite3.Error as e:
113+
raise DBException(
114+
f"Error while excuting a request to DB and fetching result: {e}"
115+
) from e
104116

105117
return result
106118

src/numbat/exceptions.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,10 @@ class NumbatException(Exception):
2323
pass
2424

2525

26+
class DBException(NumbatException): # noqa: D101
27+
pass
28+
29+
2630
class SerializeException(NumbatException): # noqa: D101
2731
pass
2832

0 commit comments

Comments
 (0)