Convert string with partially invalid encoding --> valid encoding

I have a black-box function:

my_format_error(input1, input2) ->
  % [...................]

which returns something like “some error: msg1”. And sometimes it will something like “some error: дададададада” instead of “some error: дадададада”. That is, a sub-string with invalid encoding, which is a bug.

For now, to make it simple, I need to create a function that’ll fix it:

    fix_encoding_for_my_format_error(input3)

that’ll be fed the output of the 1st function.

However, I haven’t been able to do it. I’ve been trying multiply combination of

  • unicode:characters_to_binary(…)
  • unicode:characters_to_list(…)
  • binary_to_list(…)
  • list_to_binary(…)

To no avail.

How to do it? Reliably convert a string that may, or may not, contain characters in the invalid encoding into a string which contain all the characters in the proper one.