问题
What is the best practise to do exception handling when error is thrown in different layers.
I have 4 layers of code - DAO , SERVICE , BUSINESS, PRESENTATION. I am trying to catch some run time exception in the dao layer and want it to display in the presentation layer with some message.Is the below approach a good one ?
Here in the code snippets - DataException is my runtime exception class.Service and Business exception classes are my checked exception implementation classes.
Code snippets below:
In dao layer , a method checks for some value from database
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;
}
}
In presentation layer , let it be a controller class
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;
}
}
Assume from the presentation layer message is thrown to the user in the front end JSP page ..
回答1:
You should encapsulate the business exception in a PresentationException with a code. This code is used to render the error message in a localized way. The code allows the error message to be purely in the presentation and have different messages for different views.
try{
getUser(...);
}catch(BusinessException b){
throw new PresentationException(ErrorEnum.GetUserError,b);
}
This execption should be put in the model (view context) somehow.
In the JSP you can do something like:
if(exception){
if(debug) print(exception.getCause().getMessage());
else print(localize(exception.getErrorCode());
}
来源:https://stackoverflow.com/questions/9238180/best-practise-exception-handling-in-service-dao-business-layers