def ascii_to_hex(exception):
    """ On unicode decode error (bytes -> unicode error), tries to replace
    invalid unknown bytes by their hex notation.
    """
    if isinstance(exception, UnicodeDecodeError):
        obj = exception.object
        start = exception.start
        end = exception.end
        invalid_part = obj[start:end]
        result = []
        for character in invalid_part:
            if isinstance(character, str):
                result.append(u'\\x{}'.format(character.encode('hex')))
            elif isinstance(character, int):
                result.append(u'\\{}'.format(hex(character)[1:]))
            else:
                raise exception
        result = ''.join(result), end
        return result
    raise exception
