我应该在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 ...
}

最新更新