如何缩短 Rails 5 中的异常处理消息?

How to shorten Exception Handling Message in Rails 5?

我正在做一个 Rails 项目并在其中使用异常处理,我是这样使用它的:

    begin
        @profile.update(profile_params)
        flash[:success] = SUCCESS_MESSAGE_FOR_PROFILE_UPDATED 
        redirect_to params[:referrer]
    rescue => e
        flash[:alert] = "#{e.message}"
        render :edit
    end

发生异常时,会生成一条很长的消息:

PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "index_companies_on_name" DETAIL: Key (name)=(Test2) already exists. : UPDATE "companies" SET "name" = , "updated_at" =  WHERE "companies"."id" = 

我们可以看到异常是由于 'name' 的重复条目而发生的,所以基本上我只想显示 DETAIL 部分,即“Key (name)=(Test2) 已经存在。"

您拥有的是数据库级别的验证(约束),这很好。

除此之外,您总是希望添加模型验证。

在您的情况下,它将如下所示:

validates :name, uniqueness: true

它将确保验证和适当的消息,当

@profile.update(profile_params)

由于验证无法更新记录。

可以在 @profile.errors 中找到该消息。

使用这样的设置,您将不需要 begin rescue,只需将其更改为:

if @profile.update(profile_params)
  flash[:success] = SUCCESS_MESSAGE_FOR_PROFILE_UPDATED
  redirect_to params[:referrer]
else
  render :edit
end

表单将立即包含验证错误。