我目前正在处理异常处理,我想知道应该在哪里捕获它们。
这是 GWT 应用程序的堆栈:
- 具有可以抛出 NumerFormatExeption 的方法的助手 (FormHelper.java)
- 使用此助手的小部件 (CostWidget.java)
- 调用此小部件来检索数据的演示者 (BuildingPresenter.java)
FormHelper.java
public static Integer prepareIntegerForDb(String string) {
return Integer.parseInt(string);
}
CostWidget.java
public DetailCostProxy getCostDetail() {
...
costDetail.setQuantity(FormHelper.prepareDoubleForBd(qtTextBox.getText()));
...
return costDetail;
}
public List<DetailCostProxy> getCostList() {
...
costDetails .add(ligneCout.getCostDetail());
...
}
BuildingPresenter.java
public void saveBuilding(final BuildingProxy inter, final CollectRequestContext savecontext) {
savecontext.save(display.getCostWidget().getCoutList()).fire(new Receiver<BuildingProxy >() {....
}
我正在考虑:
1) 在帮助器中的prepareIntegerForDb()中添加“抛出NumberFormatException”
2) 在小部件中的 getCostDetail() 中添加“抛出 NumberFormatException”
3) 在小部件中的 getCostList() 中添加“抛出 NumberFormatException”
4) 在演示者中缓存异常(在 saveBuilding 中)
目标是:
- 记录异常
- 向用户提供一条消息,说明出现问题
考虑到这是一个示例,您对此方法有何看法,我必须将此模式应用到整个应用程序(超过 20 个演示者)。
我的方法是处理 GWT 异常的好方法吗?或者我应该直接在帮助程序或其他地方记录错误?
最佳答案
prepareIntegerForDB() 应该抛出异常。当 Integer.parse() 失败时,这种情况会自动发生,并且您不必实际抛出异常。
getCostDetail() 应明确捕获并抛出异常,并可能详细说明抛出异常的原因。类似“成本的格式不可读”。该方法仅负责这一行。
getCostList() 应该捕获并处理异常。该方法负责整个集合。如果在这里不处理坏数据,就会丢失好数据。这是处理不良数据的一种方法。
public List<DetailCostProxy> getCostList() {
...
try {
DetailCostProxy cost = lineCount.getCostDetail()
costDetails.add(cost);
catch (NumberFormatException e) {
costDetails.add(null);
}
...
}
最后,向用户显示数据的方法应该在显示之前解释传递给它的数据。如果您使用上面的示例,这就像检查空值一样简单。
关于java - Java 中的异常处理 (GWT),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21337100/