我有一个三轮架构的应用程序。我不明白如何在这种情况下处理异常。我收集了一些问题:多层架构中的异常处理最佳实践
1。我是否需要创建一个通用异常,如PersistentException
,并使所有DAO类方法只抛出一种类型 - PersistentException
?即在每个DAO方法(CRUD)内部都这样做:
public create(Entity instance) {
try {
...// all operations here
} catch(Exception e) {
throw new PersistentException(e);
}
}
2。每个 EJB服务创建一个的异常类是可以的(每个EJB接口有一个异常)?
I.e.假设我有一个EJB豆状PersonManagementBean
,OrganizationManagementBean
,EmployeeManagementBean
相应@local
和@remote
接口。它们暴露给客户,即事实上它们是会话外观(所以它们位于服务层)。所以最好为每个bean创建相应的Exception类(PersonManagementException
,OrganizationManagementException
,EmployeeManagementException
)?
或者最好是只叫ServiceException
(如DAO中的情况下)一个例外?
3。哪种类型的例外可能会导致我的服务(繁忙)级别(,通常情况下为)?我可以将DAO(PersistentException
)异常传播给客户吗?即
public void relocatePerson() {
try {
Person p = personDao.getPerson(); // can throw PersistentException
....
if (someCondition) {
throw new PersonManagementException(); // throwing same PersonManagementException
}
....
} catch(PersonManagementException e) {
throw e; //don't need to rewrap same exception
} catch(PersistentException e) {
throw e; // DO I need to throw it as PersistentException to client? Or it's better to rewrap it as PersonManagementException?
} catch(Exception e) {
throw new PersonManagementException(e) //throwing all exception as service specific exception
}
}
或者我需要重新抛出所有异常(通常情况下)作为特定于服务的异常?
- “在通常情况下”我的意思是,我知道,在某些情况下,一些方法可以抛出其他例外有一些有用的信息(例如
ValidationException
与有关哪些对象没有通过验证规则)
好的,谢谢。但是,你能否更深入地解释一下这个词:“非常小心,不要用冗余异常类来增加远程接口的负担。如果我的每个远程方法都会被标记为“抛出MyExecption”?什么与它?什么类型的异常必须由EJB抛出 - 检查或未检查的异常?谢谢 – MyTitle
您声明的所有异常都必须包含在客户端JAR依赖项中。如果他们没有带来商业价值,他们只是自重。由于所有的EJB异常都必须扩展'RemoteException',因此在checked和unchecked之间没有选择。 –
你确定吗?我认为扩展'RemoteException'并不是强有力的要求(至少在EJB 3.0中)。我有扩展'Exception'的经验,而不是'RemoteException'。 – MyTitle