23tux
23tux

Reputation: 14746

invalid byte sequence in UTF-8 with Rails flash messages

we use Rails 3 and Spree Commerce for our online shop and we have a payment provider, that returns errors in a redirect URL if some occur. When an error occurs, we present that string with flash messages to the user.

Yesterday, something didn't work, and the payment provider returned this string in the redirect URL, which should be presented to the user inside a flash message:

errormsg=Bitte+versuchen+Sie+es+sp%E4ter+nochmals.

I debugged a little bit, and the string looks like this when decoded (e.g. is written to flash[:error]):

Bitte versuchen Sie es sp\xE4ter nochmals.

And after that, an error is raised, when rails tries to render the flash message:

invalid byte sequence in UTF-8

Can someone tell me, how to fix this? The error should contain a german ä and not \xE4. I tried setting # encoding: utf-8 to the beginning of the controller and the view, but this doesn't help.

Upvotes: 2

Views: 2081

Answers (1)

Martin M
Martin M

Reputation: 8668

'Obviously, your payment provider uses ISO-8859-1 or similar to send german umlauts.
As your rails app uses UTF-8, you can convert the message of your provicder.

Assume you stored the message in variable msg, use

utf_msg = params[:errormsg].force_encoding('ISO-8859-1').encode('UTF-8')

you can also check, if the resulting encoding is valid:

uft_msg.valid_encoding?

and outpunt a different message to avoid errors.

Upvotes: 3

Related Questions