2014-09-03 54 views
1

我們有一個分層架構,並希望在應用程序服務層控制異常處理。它下面的圖層將拋出必要的異常,但服務層將提供包裝到外觀層,以便外觀層可以期望一致的異常類。Spring自動裝配組件的異常處理

但是,服務層使用自動裝配的組件,基本上所有的錯誤都包裝在Spring異常(和休眠)類中。由於這不在方法級別,我如何將它們封裝到一致的服務級別異常類中?有關服務層如何控制Spring異常類中包含的異常的任何想法。如果這個問題聽起來太模糊,我很抱歉,但如果需要,我可以提供更多細節。我們不使用Spring MVC。下面

例子:

@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的異常?

+0

一些代碼示例將很有用:) – 2014-09-03 19:31:45

+0

添加示例代碼.. – mrbean 2014-09-03 23:23:06

回答

3

我不會,只要你不想處理這些後來的宣佈任何額外的異常..

@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; 

}

這種設計可以降低您的代碼複雜度。您可能會喜歡這一點,特別是在您項目的測試階段。您還有一個清晰的設計和一個專門的組件,僅用於處理異常。

+0

謝謝Marek。這種方法應該可行。將嘗試這一個。非常感謝您的建議 – mrbean 2014-09-04 15:51:51