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

问题描述

我有一个使用不同方法的 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 层捕获并翻译异常,然后在服务层捕获翻译后的异常来决定要做什么。

为什么要捕获并翻译?因为简单的 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 ...
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...