2012-02-11 130 views
0

當在不同層中引發錯誤時,執行異常處理的最佳做法是什麼?最佳實踐 - 服務/ dao /業務層中的異常處理

我有4層代碼 - DAO,SERVICE,BUSINESS,PRESENTATION。我試圖在dao層捕獲一些運行時異常,並希望它在表示層中顯示一些消息。下面的方法是一個好的方法嗎?

這裏的代碼片段 - DataException是我的運行時異常class.Service和Business異常類是我檢查的異常實現類。下面

代碼片段:

在DAO層,對於某些值的方法檢查從數據庫

class dao{ 
public User getUser() throws DataException{ 

User user = null; 

try 
{ 
//some operation to fetch data using hibernatetemplate 
}catch(Exception ex){ 
throw new DataException(ex.getMessage()); 
} 

return user; 
} 
} 

service.java

class service{ 
public User getUser(String username) throws ServiceException{ 

User user = null; 

try 
{ 
//some operation to fetch data using dao method 
dao.getuser(username); 
}catch(DataException ex){ 
throw new ServiceException(ex.getMessage()); 
} 

return user; 
} 
} 

business.java

class business{ 
public User getUser(String username) throws BusinessException{ 

User user = null; 

try 
{ 
//some operation to fetch data using dao method 
service.getuser(username); 
}catch(ServiceException ex){ 
throw new BusinessException(ex.getMessage()); 
} 

return user; 
} 
} 

在pre sentation層,讓它成爲一個控制器類

class Presentation{ 
public User getUser(String username) throws BusinessException{ 

    User user = null; 


//some operation to fetch data using business method 
business.getUser(username); 

    return user; 
} 
} 

從表現層消息假定被掀翻在前端JSP頁面的用戶..

回答

2

你應該封裝業務異常與一個PresentationException碼。此代碼用於以本地方式呈現錯誤消息。該代碼允許錯誤消息純粹在演示文稿中,並針對不同的視圖具有不同的消息。

try{ 
    getUser(...); 
}catch(BusinessException b){ 
    throw new PresentationException(ErrorEnum.GetUserError,b); 
} 

該方法應該以某種方式放入模型(視圖上下文)中。

在JSP中,你可以這樣做:

if(exception){ 
if(debug) print(exception.getCause().getMessage()); 
else print(localize(exception.getErrorCode()); 
}