gpt4 book ai didi

ruby-on-rails - ActiveRecord 异常不在服务对象中抛出

转载 作者:太空宇宙 更新时间:2023-11-03 17:29:26 24 4
gpt4 key购买 nike

在构建服务对象时,RecordInvalid 异常没有在应该抛出的时候抛出。相反,else block 中的代码每次都会运行。

# services/new_registration_service.rb
class NewRegistrationService

...

def perform
begin
account_create
rescue ActiveRecord::RecordInvalid => exception
OpenStruct.new(success?: false, user: user, account: account, error: exception.message)
else
# this is running every time
OpenStruct.new(success?: true, user: user, account: account, error: nil)
end
end

private

...

def account_create
# this is NOT saving, which I believe should
# throw the exception in the perform method
post_account_setup if account.save
end

...

end

这是我根据规范运行的内容,其中需要 account: name:

post :create, params: { account: FactoryBot.attributes_for(:account, { name: nil }) }

即使我 put 返回的 account.name 值,它也是 nil...这应该踢 RecordInvalid 异常。

# models/account.rb
class Account < ApplicationRecord
resourcify
has_many :users
validates :name, presence: true
end

有什么想法吗?

最佳答案

def account_create
# Instead of this:
post_account_setup if account.save

# Do this:
account.save!
post_account_setup
end

调用 save 而不是 save! 不会引发异常;它只会返回 false

或者,有些人会争辩说像这样使用异常来控制流程是不好的做法。因此,您可以这样做:

def perform
# ...
if account.valid?
account.save! # This should never fail!
post_account_create
OpenStruct.new(success?: true, user: user, account: account, error: nil)
else
OpenStruct.new(success?: false, user: user, account: account, error: account.errors)
end
end

或者,类似地:

def perform
# ...
if account.save
post_account_create
OpenStruct.new(success?: true, user: user, account: account, error: nil)
else
OpenStruct.new(success?: false, user: user, account: account, error: account.errors)
end
end

关于ruby-on-rails - ActiveRecord 异常不在服务对象中抛出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50258128/

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