]> git.ipfire.org Git - thirdparty/samba.git/commitdiff
samba-tool: add decorator to catch exception types
authorDouglas Bagnall <douglas.bagnall@catalyst.net.nz>
Sat, 9 Aug 2025 04:27:42 +0000 (16:27 +1200)
committerDouglas Bagnall <dbagnall@samba.org>
Wed, 20 Aug 2025 04:34:37 +0000 (04:34 +0000)
Often we [think we] know that all exceptions of a certain type should
be formatted as CommandErrors (i.e., the traceback is suppressed, and
the message is assumed intelligible). Rather than riddling .run() with
try...except blocks to do this, we can

@exception_to_command_error(ModelError)
def run(...)

which makes any ModelError into a CommandError in that samba-tool command.

Signed-off-by: Douglas Bagnall <douglas.bagnall@catalyst.net.nz>
Reviewed-by: Gary Lockyer <gary@catalyst.net.nz>
python/samba/netcmd/__init__.py

index 9aa4664418a5ced69e6a7ade44bdf0ee8d8df30f..3ab683ca66441b589012f56d9e4d5bc2315b0823 100644 (file)
@@ -500,3 +500,21 @@ class CommandError(Exception):
 
     def __repr__(self):
         return "CommandError(%s)" % self.message
+
+
+def exception_to_command_error(*exceptions):
+    """If you think all instances of a particular exceptions can be
+    turning to a CommandError, do this:
+
+    @exception_to_command_error(ValueError, LdbError):
+    def run(self, username, ...):
+        # continue as normal
+    """
+    def wrap2(f):
+        def wrap(*args, **kwargs):
+            try:
+                return f(*args, **kwargs)
+            except exceptions as e:
+                raise CommandError(e)
+        return wrap
+    return wrap2