EJB - 异常处理

EJB是企业应用程序的一部分,通常基于分布式环境.因此,除了可能发生的正常异常之外,还可能存在通信故障,安全权限,服务器故障等异常.

EJB容器以两种方式考虑异常 :

  • 应用程序异常 : 如果违反业务规则或在执行业务逻辑时发生异常.

  • 系统异常 : 任何异常,不是由业务逻辑或业务代码引起的. RuntimeException,RemoteException是SystemException.例如,EJB查找期间出错. RuntimeException,RemoteException是SystemException.

EJB容器如何处理异常?

何时

当发生系统异常时,EJB容器拦截异常,回滚事务并开始清理任务.它将异常包装到RemoteException中并将其抛出到客户端.

处理应用程序异常

应用程序异常通常在Session EJB方法中抛出,因为它们是负责执行业务逻辑的方法.应该在业务方法的throws子句中声明应用程序异常,并且应该在业务逻辑失败的情况下抛出.

@Stateless
public class LibraryPersistentBean implements LibraryPersistentBeanRemote {
	
   ...

   public List<Book> getBooks() throws NoBookAvailableException {        
      List<Book> books = 
         entityManager.createQuery("From Books").getResultList();
      if(books.size == 0)
		throw NoBookAvailableException
           ("No Book available in library.");
      return books;
   }
   ... 
}

处理系统例外

系统异常可能在任何时候发生,如命名查找失败,获取数据时发生sql错误.在这种情况下,这种异常应该包装在EJBException下并抛回客户端.

@Stateless
public class LibraryPersistentBean implements LibraryPersistentBeanRemote {
	
   ...

   public List<Book> getBooks() {   
      try {
         List<Book> books = 
            entityManager.createQuery("From Books").getResultList();
      } catch (CreateException ce) {
         throw (EJBException) new EJBException(ce).initCause(ce);
      } catch (SqlException se) {
         throw (EJBException) new EJBException(se).initCause(se);    
      }	  
      return books;
   }
   ... 
}

在客户端,处理EJBException.

public class EJBTester {
   private void testEntityEjb() {
   ...
   try{
      LibraryPersistentBeanRemote libraryBean =
      LibraryPersistentBeanRemote)ctx.lookup("LibraryPersistentBean/remote");
   
      List<Book> booksList = libraryBean.getBooks();
   } catch(EJBException e) {
      Exception ne = (Exception) e.getCause();
      if(ne.getClass().getName().equals("SqlException")) {
         System.out.println("Database error: "+ e.getMessage());
      }
   }
   ...
   }
}