From fd0e1175795ac3a5497dcf72ed250077abaf2ed1 Mon Sep 17 00:00:00 2001 From: Flaper Fesp Date: Thu, 11 Jul 2013 15:28:49 +0200 Subject: [PATCH] Encode error messages before sending them to stdout When an error with non-ascii characters is caught by glanceclient, it fails at printing it and exists with a UnicodeEncodedError. This patch encodes errors' messages using strutils before sending them to stdout. Fixes bug: #1200206 Change-Id: I4dabcd76ffb258840bd6a66ad23c030f34960e86 --- glanceclient/common/utils.py | 12 ++++++++++++ glanceclient/shell.py | 2 +- tests/test_utils.py | 15 +++++++++++++++ 3 files changed, 28 insertions(+), 1 deletion(-) diff --git a/glanceclient/common/utils.py b/glanceclient/common/utils.py index 49976ac6..c0e65db0 100644 --- a/glanceclient/common/utils.py +++ b/glanceclient/common/utils.py @@ -202,3 +202,15 @@ def getsockopt(self, *args, **kwargs): lands in mainstream packages. """ return self.fd.getsockopt(*args, **kwargs) + + +def exception_to_str(exc): + try: + error = unicode(exc) + except UnicodeError: + try: + error = str(exc) + except UnicodeError: + error = ("Caught '%(exception)s' exception." % + {"exception": exc.__class__.__name__}) + return strutils.safe_encode(error, errors='ignore') diff --git a/glanceclient/shell.py b/glanceclient/shell.py index aea3a7a9..e0124e5c 100644 --- a/glanceclient/shell.py +++ b/glanceclient/shell.py @@ -472,5 +472,5 @@ def main(): print >> sys.stderr, '... terminating glance client' sys.exit(1) except Exception as e: - print >> sys.stderr, e + print >> sys.stderr, utils.exception_to_str(e) sys.exit(1) diff --git a/tests/test_utils.py b/tests/test_utils.py index 138ce879..d47c7bb3 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -93,3 +93,18 @@ class TestUtils(testtools.TestCase): | Key | Value | +----------+-------+ ''') + + def test_exception_to_str(self): + class FakeException(Exception): + def __str__(self): + raise UnicodeError() + + ret = utils.exception_to_str(Exception('error message')) + self.assertEqual(ret, 'error message') + + ret = utils.exception_to_str(Exception('\xa5 error message')) + self.assertEqual(ret, ' error message') + + ret = utils.exception_to_str(FakeException('\xa5 error message')) + self.assertEqual(ret, "Caught '%(exception)s' exception." % + {'exception': 'FakeException'})