在不同层中引发错误时,执行异常处理的最佳做法是什么。
我有4层代码 - DAO,SERVICE,BUSINESS,PRESENTATION。我试图在dao层中捕获一些运行时异常,并希望它在表示层中显示一些消息。下面的方法是一个好的吗?
这里在代码片段中--DataException是我的运行时异常类.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;
}
}
在表示层中,让它成为控制器类
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页面中的用户..
答案 0 :(得分:2)
您应该使用代码将业务异常封装在PresentationException中。此代码用于以本地化方式呈现错误消息。该代码允许错误消息纯粹出现在演示文稿中,并为不同的视图提供不同的消息。
try{
getUser(...);
}catch(BusinessException b){
throw new PresentationException(ErrorEnum.GetUserError,b);
}
这个execption应该以某种方式放在模型(视图上下文)中。
在JSP中,您可以执行以下操作:
if(exception){
if(debug) print(exception.getCause().getMessage());
else print(localize(exception.getErrorCode());
}