From 84f790e67f2d35e5d4ab3fc900a50e757054a4cf Mon Sep 17 00:00:00 2001 From: Michael Hanselmann <hansmi@google.com> Date: Fri, 13 Aug 2010 19:19:07 +0200 Subject: [PATCH] errors: Function to check whether value is encoded error Signed-off-by: Michael Hanselmann <hansmi@google.com> Reviewed-by: Iustin Pop <iustin@google.com> --- lib/errors.py | 28 ++++++++++++++++++++++------ test/ganeti.errors_unittest.py | 9 +++++++++ 2 files changed, 31 insertions(+), 6 deletions(-) diff --git a/lib/errors.py b/lib/errors.py index f03d65903..9374978da 100644 --- a/lib/errors.py +++ b/lib/errors.py @@ -394,17 +394,33 @@ def EncodeException(err): return (err.__class__.__name__, err.args) -def MaybeRaise(result): - """If this looks like an encoded Ganeti exception, raise it. +def GetEncodedError(result): + """If this looks like an encoded Ganeti exception, return it. This function tries to parse the passed argument and if it looks - like an encoding done by EncodeException, it will re-raise it. + like an encoding done by EncodeException, it will return the class + object and arguments. """ tlt = (tuple, list) if (isinstance(result, tlt) and len(result) == 2 and isinstance(result[1], tlt)): # custom ganeti errors - err_class = GetErrorClass(result[0]) - if err_class is not None: - raise err_class, tuple(result[1]) + errcls = GetErrorClass(result[0]) + if errcls: + return (errcls, tuple(result[1])) + + return None + + +def MaybeRaise(result): + """If this looks like an encoded Ganeti exception, raise it. + + This function tries to parse the passed argument and if it looks + like an encoding done by EncodeException, it will re-raise it. + + """ + error = GetEncodedError(result) + if error: + (errcls, args) = error + raise errcls, args diff --git a/test/ganeti.errors_unittest.py b/test/ganeti.errors_unittest.py index d5a37b646..ec25912c6 100755 --- a/test/ganeti.errors_unittest.py +++ b/test/ganeti.errors_unittest.py @@ -62,6 +62,15 @@ class TestErrors(testutils.GanetiTestCase): self.assertRaises(errors.GenericError, errors.MaybeRaise, ("GenericError", ["Hello"])) + def testGetEncodedError(self): + self.assertEqualValues(errors.GetEncodedError(["GenericError", + ("Hello", 123, "World")]), + (errors.GenericError, ("Hello", 123, "World"))) + self.assertEqualValues(errors.GetEncodedError(["GenericError", []]), + (errors.GenericError, ())) + self.assertFalse(errors.GetEncodedError(["NoErrorClass", + ("Hello", 123, "World")])) + if __name__ == "__main__": testutils.GanetiTestProgram() -- GitLab