Where and how handle spring+hibernate exceptions?
im using spring+hibernate for a desktop application.
I'm trying to build it with a layered implementation, so i have:
GUI layer --call--> Service layer --call--> DAO layer
A small example to better exaplain my situation:
// In GUI layer
private void actionPerformed(ActionEvent evt){
addUser();
}
private void addUser(){
// Check gui validation for user inputs
if(inputIsValid()){
String username=nameText.getText();
String pass=passText.getText();
//Now call service layer
userService.createUser(username, pass);
// Now here i want to show a message to user like
// "Operation successful" or "Operation failed"
// or more sofisticated message like "User with same name already exists"
}
}
// Service layer
@Transactional
public void createUser(String name, String pass){
User user=new User(name, pass);
userDao.save(user);
}
// Another serv开发者_如何学JAVAice layer example,
@Transactional
public boolean createUser(String name, String pass){
User user=new User(name, pass);
try{
userDao.save(user);
}
catch(Exception ex){
Log(ex);
return false;
}
return true;
// In this case GUI layer can know if save is succesful, but it can't know WHY
// the save is failed : some username? DB service shutdown? etc..
}
The problem is: who throw exception and who handle it?
I think DAO have to throw first exception, and service layer rethrow it, and finally GUI layer handle exception, so i can show message to user, is this good? There is a way to build some ExceptionHandler using spring?
What is the best practice to manage exceptions using spring+hibernate?
Thanks.
I would suggest wrapping the thrown exceptions in your own exception class and letting them bubble up to the GUI layer.
If you're using Spring MVC, then there's a solution of writing ExcpetionHandlerResolver
, take at the look on the documentation
If you're not working with Spring MVC. i would suggest throwing the exception from DAO to Service and then to View layer. Only the view layer can really provide valuable information to the user based on the exception caught.
精彩评论