Skip to content

Commit 5b39e60

Browse files
author
Han Wang
committed
better error handeling
1 parent 248ef5a commit 5b39e60

2 files changed

Lines changed: 17 additions & 4 deletions

File tree

dpdata/lmdb/format.py

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,18 @@
1313
m.patch()
1414

1515

16+
class LMDBError(Exception):
17+
"""Base class for LMDB errors."""
18+
19+
20+
class LMDBMetadataError(LMDBError):
21+
"""Metadata not found in LMDB."""
22+
23+
24+
class LMDBFrameError(LMDBError):
25+
"""Frame data not found in LMDB."""
26+
27+
1628
class LMDBFormat(Format):
1729
"""
1830
Class for handling the LMDB format, which stores atomic configurations in a
@@ -194,7 +206,7 @@ def from_multi_systems(self, file_name, map_size=1000000000, **kwargs):
194206
with env.begin() as txn:
195207
metadata_packed = txn.get(b"__metadata__")
196208
if metadata_packed is None:
197-
raise KeyError("LMDB database does not contain metadata.")
209+
raise LMDBMetadataError("LMDB database does not contain metadata.")
198210
metadata = msgpack.unpackb(metadata_packed, raw=False)
199211
frame_idx_fmt = metadata.get("frame_idx_fmt", "012d")
200212

@@ -209,7 +221,7 @@ def from_multi_systems(self, file_name, map_size=1000000000, **kwargs):
209221
key = f"{i:{frame_idx_fmt}}".encode("ascii")
210222
value = txn.get(key)
211223
if value is None:
212-
raise KeyError(f"Frame data not found for key: {key}")
224+
raise LMDBFrameError(f"Frame data not found for key: {key}")
213225
frame_data = msgpack.unpackb(value, raw=False)
214226
system_frames.append(frame_data)
215227

tests/test_lmdb.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
)
1818
from context import dpdata
1919

20+
from dpdata.lmdb.format import LMDBFrameError, LMDBMetadataError
2021
from dpdata.plugins.lmdb import LMDBFormat
2122

2223

@@ -128,13 +129,13 @@ def test_load_missing_metadata(self):
128129
).close() # Creates empty LMDB environment
129130

130131
with self.assertRaisesRegex(
131-
KeyError, "LMDB database does not contain metadata."
132+
LMDBMetadataError, "LMDB database does not contain metadata."
132133
):
133134
LMDBFormat().from_multi_systems(self.lmdb_path_missing_metadata)
134135

135136
def test_load_missing_frame_data(self):
136137
with self.assertRaisesRegex(
137-
KeyError, "Frame data not found for key: b'000000000000'"
138+
LMDBFrameError, "Frame data not found for key: b'000000000000'"
138139
):
139140
LMDBFormat().from_multi_systems(self.lmdb_path_missing_frame)
140141

0 commit comments

Comments
 (0)