我们有一个分层的体系结构,希望在应用程序服务层控制异常处理。它下面的层将抛出必要的异常,但是服务层将向facade层提供包装器,这样facade层就可以期望得到一致的异常类。
但是,服务层使用的是自动配置的组件,基本上所有错误都封装在spring异常(和hibernate)类中。由于这不是在方法级别,所以如何将它们包装成一致的服务级别异常类?任何关于服务层如何控制包装在spring异常类中的异常的想法。如果这个问题听起来太含糊,我很抱歉,但如果需要的话,我可以提供更多的细节。我们没有使用spring。
例子如下:
@Service("RuleService")
@Transactional
public class RuleService implements IRuleService {
@Autowired
IPersistenceManager<IRuleBO, Long> pMgrRule;
public AppServiceResponse createRule(RuleDTO ruleDTO) throws ApplicationException, ServerException {
try {
//do something
}
catch (PersistenceException pe) {
throw new ApplicationException (pe);
}
catch (ServerException se) {
throw se;
}
catch (Exception e) {
throw new ApplicationException (e);
}在持久化层,它就像是..。
@Transactional
public T save(T entity) throws ServerException, PersistenceException {
try {
getSession().saveOrUpdate(entity);
return entity;
}
catch (JDBCException je) {
throw new PersistenceException(je);
}
catch (QueryException qe) {
throw new PersistenceException(qe);
}
catch (NonUniqueResultException nre) {
throw new PersistenceException(nre);
}
catch (HibernateException he) {
throw new ServerException(he);
}
}如您所见,我们希望从服务层返回ApplicationException。但是,由于组件是自动加载的,因此任何数据库连接错误都会导致HibernateException封装在SpringException中。有办法控制Spring的异常吗?
发布于 2014-09-04 08:05:24
我不会声明任何额外的异常,只要您以后不想处理它们。
@Service("RuleService")
@Transactional
public class RuleService implements IRuleService {
@Autowired
IPersistenceManager<IRuleBO, Long> pMgrRule;
public AppServiceResponse createRule(RuleDTO ruleDTO) throws ApplicationException {
//
persistenceService.save(myEntity);
}坚持就像
@Transactional
public T save(T entity){
getSession().saveOrUpdate(entity);
}然后,您可以创建一个ExceptionHandler方面来处理服务层的所有异常,并将它们包装到ApplicationException中。
@Aspect
public class ExceptionHandler {
@Around("execution(public * xxx.xxx.services.*.*(..))")
public Object handleException(ProceedingJoinPoint joinPoint) throws Throwable {
Object retVal = null;
try {
retVal = joinPoint.proceed();
}
catch (JDBCException jDBCException ) {
throw new ApplicationException(jDBCException);
}
catch (JpaSystemException jpaSystemException) {
throw new ApplicationException(jDBCException);
}
// and others
return retVal;}
这种设计可以降低您的代码复杂度。您可能会欣赏这一点,特别是在项目的测试阶段。这里还有一个清晰的设计和一个只用于处理异常的特殊组件。
https://stackoverflow.com/questions/25649201
复制相似问题