Elixir integer list to string causes (UnicodeConversionError) invalid code point

The problem

I need to create a string interpolating a list of integers in it.

"""
SomeQuery {
  someQuery(articleIds: #{inspect(article_ids)}) {
    edges {
      node {
        id
      }
    }
  }
}
"""

Failing example

For example, the list [725553234] makes the example above to fail:

article_ids = [725553234]

"""
SomeQuery {
  someQuery(articleIds: #{article_ids}) {
    edges {
      node {
        id
      }
    }
  }
}
"""
** (exit) an exception was raised:
    ** (UnicodeConversionError) invalid code point 725553234
        (elixir) lib/list.ex:839: List.to_string/1
        (commsapp_api) lib/my_project/client.ex:70: CommsappApi.News.Clients.CommunicationMs.Client.articles_feed/3

System

Erlang/OTP 20 [erts-9.3] [source] [64-bit] [smp:8:8] [ds:8:8:10]
[async-threads:10] [hipe] [kernel-poll:false] [dtrace]

Elixir 1.6.3 (compiled with OTP 20)

Tried solutions

It tried the following:

  • Using inspect is not working: articleIds: #{inspect(article_ids)}
  • Using the IO.inspect with the :char_lists opt with :as_list: IO.inspect(article_ids, char_lists: :as_lists
  • Trying to join the integer list as string with: articleIds: [#{Enum.join(article_ids, ", ")}]
  • Interpolating the integers parsed to string with: Enum.map(article_ids, &Integer.to_string/1) |> Enum.join(", ")
  • I tried using a single line instead of a multiline string, not working
  • Many things I don’t remember after trying different solutions… >.<

Guesses

The problem comes when using the brackets in the string, Elixir treats the interporlation as a list and raises the error because it cannot find the codepoints.

Ideas?

Thanks in advance!

So I assume you actually want to display as a list of numbers?

Such that the line gets interpolated to someQuery(articleIds: [725553234]) {?

Then you need to change it to say #{inspect article_ids}.

The implementation of String.Chars for List will always try to interpret a List as a char list.

You might need to play a bit with the options passed to inspect though.

Especially setting higher :limit or :printable_limit might be necessary, also depending on how low your IDs can be, you might even need to set charlists: :as_lists.

2 Likes