我在持久化我的实体时使用了 EJB3/JPA,我很高兴它能够管理我的数据库相关 任务。 我唯一关心的是异常处理。我保存实体时的示例代码总是采用这种风格。 我在网上阅读的大多数教程都是这种风格,也没有考虑异常处理。
@Stateless
public class StudentFacade{
@PersistenceContext(unitName = "MyDBPU")
private EntityManager em;
public void save(Student student) {
em.persist(student);
}
}
但我不知道 EJB 应用程序中异常处理的最佳方式是什么? 处理异常的最佳方式应该是什么?
这是其他人处理异常的方式吗?在您的 session 外观上使用 try catch block ?
@Stateless
public class StudentFacade{
@PersistenceContext(unitName = "MyDBPU")
private EntityManager em;
public void save(Student student) {
try {
em.persist(student);
} catch(Exception e) {
//log it or do something
}
}
}
还是让方法抛出异常?
public void save(Student student) throws Exception {
em.persist(student);
}
不知道我的理解是否正确,因为我还在学习EJB。 谢谢
最佳答案
异常处理的想法是在发生任何故障时在单点执行一些逻辑。 try catch 将在最后需要处理异常或需要将异常转换为另一个异常时使用
假设您的应用有很多层,即 Action、Facade、Persist
委托(delegate)异常 在这种情况下,在 Facade 上抛出的任何异常都可以抛给上面的操作层。 在行动中,特定的异常将被捕获并使用适当的错误消息进行处理。
//This is in Facade Layer
public void save(Student student) throws AppException{
//exceptions delegated to action layer
//call to Persist Layer
}
将一般异常转换为应用异常 说在持久性你得到和 DBException 像 sqlException。这个异常不应该被发送到 Action 或 Facade 层,所以我们捕获特定的异常然后抛出一个新的异常(应用程序的用户定义异常)
//This is in Persist Layer
public void save(Student student) throws AppException{
//converting general exception to AppException and delegating to Facade Layer
try{
em.persist(student);//call to DB. This is in Persist Layer
}catch(Exception e){
throw new AppException("DB exception", e)
}
}
Action 层 您将捕获您的异常,然后在那里处理异常
//This is in Action layer
public void callSave(Student student){
try{
//call Facade layer
}catch(AppException e){
//Log error and handle
}
}
关于java - JPA 中更好的异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7631727/