简体   繁体   中英

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 service 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.

我建议在你自己的异常类中包装抛出的异常并让它们冒泡到GUI层。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM