From 3782656569547b775f3b310ff6a226e49c0a7581 Mon Sep 17 00:00:00 2001 From: Darko Poljak Date: Tue, 4 Sep 2018 08:27:20 +0200 Subject: [PATCH] Report encoding errors nicely. --- cdist/__init__.py | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/cdist/__init__.py b/cdist/__init__.py index b7602ff8..000a571c 100644 --- a/cdist/__init__.py +++ b/cdist/__init__.py @@ -100,17 +100,23 @@ class CdistEntityError(Error): for name, path in stdpaths: if name not in result: result[name] = [] - if os.path.exists(path) and os.path.getsize(path) > 0: - output = [] - label_begin = name + ":" + header_name - output.append(label_begin) - output.append('\n') - output.append('-' * len(label_begin)) - output.append('\n') - with open(path, 'r') as fd: - output.append(fd.read()) - output.append('\n') - result[name].append(''.join(output)) + try: + if os.path.exists(path) and os.path.getsize(path) > 0: + output = [] + label_begin = name + ":" + header_name + output.append(label_begin) + output.append('\n') + output.append('-' * len(label_begin)) + output.append('\n') + with open(path, 'r') as fd: + output.append(fd.read()) + output.append('\n') + result[name].append(''.join(output)) + except UnicodeError as ue: + result[name].append(('Cannot output {}:{} due to: {}.\n' + 'You can try to read the error file "{}"' + ' yourself.').format( + name, header_name, ue, path)) return result def _stderr(self):