diff --git a/lib/errors.py b/lib/errors.py index f03d6590305edaf35df0e85b0ad191b07d55c5e2..9374978da19b7751059679c4eed6a6591ed0c878 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 d5a37b6468a16b1aefba07b66981a3a1b0174937..ec25912c60da75ed8a74396c14a4d6fbd0f52fc8 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()