我应该在 DAO 层捕获异常还是在服务层捕获异常?

Should I catch exceptions in DAO layer or can I do it on service layer?

我有一个使用不同方法的 DAO。 其中之一的示例:

@Override
public boolean insertUser(Connection connection,User user) {
    int rowNum = 0;
    String query = "INSERT INTO user_info(login,userPassword,userType,userEmail)values(?,?,?,?);";
    ResultSet keys = null;
    Connection con;
    PreparedStatement statement = null;
    try {
        con = connection;
        statement = con.prepareStatement(query,Statement.RETURN_GENERATED_KEYS);
        statement.setString(1, user.getLogin());
        statement.setString(2, PasswordUtil.generateStrongPasswordHash(user.getPassword()));
        statement.setString(3, user.getUserType());
        statement.setString(4, user.getUserEmail());
        rowNum = statement.executeUpdate();
        keys = statement.getGeneratedKeys();
        if (keys.next()) {
            user.setUserId(keys.getInt(1));
        }

    } catch (SQLException e) {
        LOGGER.error(e);
    } finally {
        ConnectionUtil.oneMethodToCloseThemAll(keys,statement,null);
        }
    return rowNum > 0;
}

在服务层我有:

public boolean insertUser(User user)  {
    Connection connection = MySQLDAOFactory.getConnection();
    boolean result =  userDao.insertUser(connection,user);
    ConnectionUtil.commit(connection);
    ConnectionUtil.oneMethodToCloseThemAll(null,null,connection);
    return result;
}

我应该在DAO层捕获异常还是抛出并在服务层捕获?

通常我在 DAO 层捕获并翻译异常,然后在服务层捕获翻译后的异常来决定做什么。

为什么要catch然后翻译?因为一个简单的SQLException很难让Service Layer理解发生了什么,所以你在DAO,把它翻译成一个更'friendly'对应的异常然后抛出,这样Service Layer就可以很容易的决定做什么。

一个简单的例子:

DAO:

try {
  // your logic to insert
} catch (SQLException e) {
  // translate the exception
  if (e.getErrorCode() == 123) // imagine 123 is a constraint violation code from the database
    throw new ConstraintViolationException("message", e);
} finally {
  // ...
}

服务层:

try {
    callMethodFromDAO();
} catch (ConstraintViolationException ex) {
    // what to do ...
} catch (AnotherDatabaseException ex) {
    // what to do ...
}