gpt4 book ai didi

ruby-on-rails - Rails 3 - 如何处理 PG 错误不完整的多字节字符

转载 作者:数据小太阳 更新时间:2023-10-29 08:19:00 31 4
gpt4 key购买 nike

在 Rails 3.2 应用程序 (Ruby 1.9.2) 中,我收到以下错误

A PGError occurred in mobile_users#update:

incomplete multibyte character

这些是 Postgres 错误,但我在开发和测试模式下测试时遇到类似的 SQLIte 错误

导致这个错误的参数是(故意省略了auth token)

  * Parameters: {"mobile_user"=>{"quiz_id"=>"1", "auth"=>"xxx", "name"=>"Joaqu\xEDn"}, "action"=>"update", "controller"=>"mobile_users", "id"=>"1", "format"=>"mobile"}

这是作为 JSON HTTP Put 请求传入的,处理此问题的更新操作如下

  # PUT /mobile_users/1
# PUT /mobile_users/1.xml
def update
@mobile_user = current_mobile_user
@mobile_user.attributes = params[:mobile_user]

respond_to do |format|
if @mobile_user.save
format.html { redirect_to(@mobile_user, :notice => 'Mobile user was successfully updated.') }
format.json { head :ok }
format.mobile { head :ok }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.json { render :json => @mobile_user.errors, :status => :unprocessable_entity }
format.mobile { render :json => @mobile_user.errors, :status => :unprocessable_entity }
format.xml { render :xml => @mobile_user.errors, :status => :unprocessable_entity }
end
end

end

上述参数中的违规字符串是“Joaqu\xEDn”,这是完全有效的。问题是我需要处理来自任何语言的所有字符集。

我假设我需要使用 iconv 库,但为了做到这一点,我需要检测要从中转换为 UTF8 的字符集,但我不知道如何执行此操作。

我还得到了 "name"=>"p\xEDa " 的 UTF-8 无效字节序列

最佳答案

这个:

"Joaqu\xEDn"

"Joaquín" 的 ISO-8859-1 编码版本,因此它不是有效的 UTF-8,您的数据库提示它是正确的。如果可能,修复您的移动客户端以在 JSON 中使用 UTF-8;如果你不能这样做,那么你可以用这个修复编码:

params[:mobile_user][:name].force_encoding('iso-8859-1').encode!('utf-8')

在服务器上。在服务器上修复它的问题是你必须猜测传入的编码是什么,而你的猜测可能不正确。没有办法可靠地猜测特定字符串的编码,有 rchardet但它不适用于最新版本的 Ruby,而且它似乎已被放弃;您也许可以修复此 gem 以使用现代 Ruby。还有一些其他猜测库,但它们似乎也都已被放弃。

JSON 文本始终为 by definition , Unicode 和 UTF-8 默认编码:

3.  Encoding

JSON text SHALL be encoded in Unicode. The default encoding is
UTF-8.

任何向您发送非 UTF-8 格式的 JSON 的客户端在我看来都是错误的,因为几乎所有内容都假定 JSON 是 UTF-8。当然,某处可能有一个指定 ISO 8859-1 的编码 header ,或者 header 可能说 UTF-8,即使它是 ISO 8859-1。

关于ruby-on-rails - Rails 3 - 如何处理 PG 错误不完整的多字节字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9167468/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com