0

In legacy code the original exception gets caught in the variable exc:

  File "/usr/lib64/python2.7/urllib2.py", line 1177, in do_open
    raise URLError(err)
URLError: <urlopen error [Errno 32] Datenübergabe unterbrochen (broken pipe)>

I want to use unicode(exc) but this fails:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 31:
                     ordinal not in range(128)

How can I create a unicode string from the exception exc?

Environment: Python 2.7

guettli
  • 25,042
  • 81
  • 346
  • 663
  • https://stackoverflow.com/questions/5096776/unicode-decodeutf-8-ignore-raising-unicodeencodeerror – Joe Jul 20 '18 at 07:58
  • You should not be writing new code in Python 2 in 2018. – tripleee Jul 20 '18 at 08:58
  • @tripleee you know more than I do. You know when the above code was written? I don't. – guettli Jul 20 '18 at 09:05
  • Obviously, maintaining Python 2 code is going to be a thing for a long time still. Your question reads like you are trying to actually develop Python 2 code, though. – tripleee Jul 20 '18 at 09:14
  • @tripleee Thank you for this hint. I updated the question. Is it correct now? – guettli Jul 20 '18 at 09:26
  • Showing the actual code which produces the exception would still be a welcome addition. See also the [help] guidance for creating a [mcve]. – tripleee Jul 20 '18 at 09:32

1 Answers1

2

This

unicode(exc)

is failing because exc is of type URLError, and if you try to do string operations on it (like converting to Unicode) Python does an implicit string conversion, and the encoding it assumes is 'ascii'. To do what you want you have to get the string out of the exception yourself, and supply the encoding you want, like this:

unicode(exc.reason, encoding='Latin-1')

For a solution that will work for other types of exception, decode the members of the tuple exc.args individually:

", ".join(unicode(a, encoding='Latin-1') for a in exc.args)

There is no generic way to tell which member of args is the one you really want to see, but it will usually be the first one.

BoarGules
  • 16,440
  • 2
  • 27
  • 44