想象一下,您有一个处理用户账户之间资金转移的上下文。
class Account < ActiveRecord::Base
belongs_to :user
end
class MoneySender < SimpleDelegator
class NotEnoughBalanceError < StandardError ; ; end
def initialize(account)
super(account)
end
def send_money(destination_account, amount)
raise NotEnoughBalanceError unless can_send?(amount)
self.transaction do
self.balance -= amount
destination_account.balance += amount
end
self.balance
end
def can_send?(amount)
self.balance >= amount
end
end
class HandleMoneyTransferContext
def initialize(source, destination, amount)
@source = source
@destination = destination
@amount = amount
end
def transfer
sender = MoneySender.new(@source
sender.send_money(@destination, @amount)
end
end
汇款由 Web 应用程序触发,处理该操作的 Rails 控制器执行类似这样的操作
class AccountsController < AplicationController
def transfer
source = Account.find(params[:id])
destination = Account.find(params[:destination_account])
HandleMoneyTransferContext.new(source, destination, params[:amount]).transfer
render 'success_page'
rescue MoneySender::NotEnoughBalanceError => e
flash[:error] = t(accounts.transfer.not_enough_money)
render 'error_page', status: 400
end
end
所以我的问题是,上下文可以引发异常吗?我应该在上下文中捕获角色异常并引发上下文异常吗?(上下文用户应该不知道正在使用哪些角色),有没有更好的解决方案?
谢谢