【问题标题】:Should I catch exceptions in DAO layer or can I do it on service layer?我应该在 DAO 层捕获异常还是在服务层捕获异常?
【发布时间】:2021-08-20 18:13:03
【问题描述】:

我有一个使用不同方法的 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 层中捕获 ,您如何期望您的程序知道出现问题?
  • @MarkRotteveel,是的,我不明白,但是当我使用数据库时有很多例外

标签: java mysql jdbc dao service-layer


【解决方案1】:

通常我在 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 ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-27
    • 1970-01-01
    • 2016-03-13
    • 1970-01-01
    • 2014-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多