Срба
Срба

Reputation: 473

Why does IronPython str() of a string object raise a UnicodeEncodeError?

Our web app utilizes custom made IronPython scripts (the IronPython version is 2.7.3)

An object in the script is converted to string at one point. It is definitely a string. It is provided by our app and its value has come from an outer system. The line that raises the exception is:

return str(customField.Value)

where customField.Value is the object I have been describing (customField.Value is of type object).

The object is a string as customField is of type text (a type from our app) and I can pull out its value, which looks like a standard English string and has no characters out of ASCII scope.

The exception logged (after processing by our logger) is:

Error on uploading case data: ('unknown', '\x00', 0, 1, '')
['Equals', 'GetHashCode', 'GetType', 'InitializeFromClr', 'Item', 'MemberwiseClone',
 'ReferenceEquals', 'ToString', '__class__', '__delattr__', '__dict__', '__doc__',
 '__format__', '__getattribute__', '__getitem__', '__getslice__', '__hash__', '__init__',
 '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__',
 '__sizeof__', '__str__', '__subclasshook__', '__unicode__', 'args', 'clsException',
 'encoding', 'end', 'message', 'object', 'reason', 'start']
message: --- ---
args: --- ('unknown', '\x00', 0, 1, '') ---
CLR Exception: --- System.Text.EncoderFallbackException ---
Error located in on line 531 in function 
Error located in on line 410 in function packData...

Why is this happening? What should I do to resolve this exception, and what is the proper way to modify the script?

Upvotes: 1

Views: 1399

Answers (1)

Срба
Срба

Reputation: 473

Resolved: str() applied on a str object that is an unicode string, with characters out of ascii scope, throws the exception described

a solution for me was to instead of str() use the following method:

def safeStringConversion(obj):
    if isinstance(obj, str):
        return obj
    else:
        return str(obj)

with this, unicode strings have been passed in preserved form througout the app

Upvotes: 4

Related Questions