Imagine that you have a context that handles money transfers between user's accounts.
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
And money transfers are triggered by a web application and the rails controller that handle that operations does something like this
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
So my question is, Is it OK for a context to raise exceptions? Should I catch the Role exception in the context and raise a context exception? (Context users should not know which roles are being used), Is there a better solution?
Thanks