当在不同的层中引发错误时,进行异常处理的最佳实践是什么?
我有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;
}
}
业务.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页面中被引发给用户。
最佳答案
您应该使用代码将业务异常封装在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());
}