Java 我应该在DAO层捕获异常,还是可以在服务层捕获异常?

Java 我应该在DAO层捕获异常,还是可以在服务层捕获异常?,java,mysql,jdbc,dao,service-layer,Java,Mysql,Jdbc,Dao,Service Layer,我有一把不同方法的刀。 其中一个示例: @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;

我有一把不同方法的刀。 其中一个示例:

@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层捕获并翻译异常,并在服务层捕获已翻译的异常,以决定做什么

为什么捕获并转换?因为一个简单的
SQLException
对服务层来说很难理解发生了什么,所以您在DAO中捕获
SQLException
,将其转换为一个更“友好”的对应异常,然后抛出它,这样服务层就可以轻松地决定做什么

一个简单的例子:

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

如果您(仅)捕获DAO层中的异常,您希望您的程序如何知道发生了错误?@MarkRotteveel,是的,我确实不理解,但当我处理数据库时,会出现很多异常