changeset 2644:e107089d6640

core (memory/persistent): better default value handling in LazyPersistentBinaryDict (don't jump to debugger in debug mode if value is not found)
author Goffi <goffi@goffi.org>
date Sun, 29 Jul 2018 18:44:49 +0200
parents 189e38fb11ff
children f2cf1daa42cb
files sat/memory/persistent.py
diffstat 1 files changed, 18 insertions(+), 8 deletions(-) [+]
line wrap: on
line diff
--- a/sat/memory/persistent.py	Sun Jul 29 18:44:27 2018 +0200
+++ b/sat/memory/persistent.py	Sun Jul 29 18:44:49 2018 +0200
@@ -20,6 +20,7 @@
 from sat.core.i18n import _
 from sat.core.log import getLogger
 log = getLogger(__name__)
+from twisted.python import failure
 
 
 class MemoryNotInitializedError(Exception):
@@ -199,26 +200,35 @@
     def __iter__(self):
         raise NotImplementedError
 
+    def _data2value(self, data, key):
+        try:
+            return data[key]
+        except KeyError as e:
+            # we return a Failure here to avoid the jump
+            # into debugger in debug mode.
+            raise failure.Failure(e)
+
     def __getitem__(self, key):
         """get the value as a Deferred"""
-        d = self.storage.getPrivates(self.namespace, keys=[key], binary=self.binary, profile=self.profile)
-        d.addCallback(lambda data: data[key])
+        d = self.storage.getPrivates(self.namespace, keys=[key], binary=self.binary,
+                                     profile=self.profile)
+        d.addCallback(self._data2value, key)
         return d
 
     def __setitem__(self, key, value):
-        self.storage.setPrivateValue(self.namespace, key, value, self.binary, self.profile)
+        self.storage.setPrivateValue(self.namespace, key, value, self.binary,
+                                     self.profile)
 
     def __delitem__(self, key):
         self.storage.delPrivateValue(self.namespace, key, self.binary, self.profile)
 
-    def _valueOrDefault(self, value, default):
-        if value is None:
-            return default
-        return value
+    def _defaultOrException(self, failure_, default):
+        failure_.trap(KeyError)
+        return default
 
     def get(self, key, default=None):
         d = self.__getitem__(key)
-        d.addCallback(self._valueOrDefault)
+        d.addErrback(self._defaultOrException, default=default)
         return d
 
     def setdefault(self, key, default):