I have a question in handling the "business validation" done on the service layer. The code belows shows a typical account fund transfer example, which validates for sufficient fund, transfer amount is lesser than defined limit.
In this example, the caller have to handle and catch the exception defined in the Action class and used the corresponding ActionError to display the error message.
It is a "must" to use exceptions for all business validation?
If I decide not to use exception for this, I will have to defined the corresponding ActionError in the business layer(which violates the coupling / cohesion) rule in a certain sense.
How should one handle the message propagating by service layer back to the Action classes?
public void transfer(String fromAccount, String toAccount, double amount) throws InsufficientFundsException, TransferLimitException, FactoryException {
try {
Account from = getAccountHome().findByPrimaryKey(
new AccountKey(fromAccount));
Account to = getAccountHome().findByPrimaryKey(
new AccountKey(toAccount));
if (from.getBalance() < amount)
throw new InsufficientFundsException(); // Add action errors
if (from.getTransferLimit() > amount)
throw new TransferLimitException(); // Add action errors
to.deposit(amount);
from.withdraw(amount);
} catch (Exception e) {
throw new FactoryException(
"cannot perform transfer. Nested exception is " + e);
}
}