我在处理服务层上完成的"业务验证"时遇到了一个问题.下面的代码显示了一个典型的账户资金转账示例,该示例验证了足够的资金,转账金额小于定义的限额.
在此示例中,调用者必须处理并捕获Action类中定义的异常,并使用相应的ActionError来显示错误消息.
所有业务验证都使用例外是"必须的"吗?
如果我决定不为此使用异常,我将必须在某种意义上在业务层(违反耦合/内聚)规则中定义相应的ActionError.
如何处理由服务层传播回Action类的消息?
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);
}
}
Run Code Online (Sandbox Code Playgroud)
您的业务应该在Model中处理,并且业务逻辑中遇到的任何问题都应该传播给调用者,在本例中是调用者Struts Action类.
但是你不想将你的Struts类(Action,ActionForm,ActionError,ActionMessage等)与Model结合,所以你基本上有两种方法可以通知调用者任何问题:
我更喜欢使用异常,因为无论执行链有多深,它们都可以从业务层内的任何位置抛到顶层.这样可以保持业务代码的清洁,因为您不必像第一种方法那样冒泡错误代码.
然后,Action类将捕获异常,这些异常将它们转换为要在View中显示的ActionError对象.只要确保你没有过度使用并最终扔掉厨房水槽,否则你的Action类将会挤满过多的try-catch块.此外,您可以让异常传播并创建某种异常处理程序,捕获从下面抛出的所有异常,并根据异常类型重定向到适当的视图.
| 归档时间: |
|
| 查看次数: |
1328 次 |
| 最近记录: |