我正在用Java编写我的第一个DAO,我想知道如何管理可能出现的异常:
我当前的代码:
public void update(User userUpdate) throws Exception {
try (Connection dbConnection = ConnectionManager.getConnection(); PreparedStatement preparedStatement = dbConnection.prepareStatement(QUERY_UPDATE);) {
int userId = userUpdate.getId();
String userName = userUpdate.getName();
String userMail = userUpdate.getEmail();
String userPassword = userUpdate.getPassword();
int userIdRole = userUpdate.getRole().getId_role();
preparedStatement.setString(1, userName);
preparedStatement.setString(2, userMail);
preparedStatement.setString(3, userPassword);
preparedStatement.setInt(4, userIdRole);
preparedStatement.setInt(5, userId);
int updatedRows = preparedStatement.executeUpdate();
if (updatedRows != 1) {
throw new Exception("We had a problem updating your details");
}
}
}我不知道如何处理异常。调用此方法的控制器有一个catch块来从DAO方法获取异常,但是,我必须有什么样的异常才能将其发送回控制器,只有全局的吗?
我是否必须捕获DAO方法中的某些内容(并创建反馈以将其发送给用户),或者只是将异常抛给控制器并让它们单独处理反馈?
谢谢!!
发布于 2020-08-04 18:56:14
通常,您将尝试从应用程序代码中封装特定的IO异常,如SQLException。因此,如果您正在使用一些泛型DAO构建一个简单的CRUD应用程序,则可以将SQLException映射到更具体的异常,如catch子句中的UpdateFailedException(),并将此异常委托给控制器。根据您将哪个框架或库用于表示逻辑,您可以将此特定异常类型映射到HTTP响应代码,并使用类似于全局错误处理程序的东西(一些crud框架支持此功能)。另一个问题是,当没有数据被更新时,它真的是一个例外吗?如果没有数据更新,没有找到给定的用户,你可以用一个前提条件来检查,并可能引发一个映射到404Http代码的NotFoundException。或者,如果用户不在数据库中,则只需创建一个,而不抛出异常。最后,它可能看起来像这样:
public class Controller {
public HttpResponse updateUserAction(User user) {
try {
userDao.update(User user);
return new HttpResonse(200, "User has been updated.");
} catch (UpdateException ex) {
return new HttpResponse(500, ex.getMessage());
} catch (NotFoundException ex) {
return new HttpResponse(404, ex.getMessage());
}
}
}
public class UserDao {
public void update(User userUpdate) throws NotFoundException, UpdateException {
try (Connection dbConnection = ConnectionManager.getConnection(); PreparedStatement preparedStatement = dbConnection.prepareStatement(QUERY_UPDATE);) {
//check if user exists pseudocode
if (this.get(userUpdate.getId()) == null) throw new NotFoundException("User not found");
int userId = userUpdate.getId();
String userName = userUpdate.getName();
String userMail = userUpdate.getEmail();
String userPassword = userUpdate.getPassword();
int userIdRole = userUpdate.getRole().getId_role();
preparedStatement.setString(1, userName);
preparedStatement.setString(2, userMail);
preparedStatement.setString(3, userPassword);
preparedStatement.setInt(4, userIdRole);
preparedStatement.setInt(5, userId);
preparedStatement.executeUpdate();
} catch (SQLException ex) {
ex.printStackTrace();
throw new UpdateException();
} catch (UpdateException ex) {
ex.prinntStackTrace();
throw ex;
}
}
}https://stackoverflow.com/questions/63244864
复制相似问题