如何在Java DAO中管理异常?

huangapple go评论72阅读模式
英文:

How to manage exceptions in a Java DAO?

问题

我正在用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("更新您的详细信息时出现问题");

	    }
	}
}

我不知道如何处理异常。调用这个方法的控制器有一个catch块来捕获DAO方法抛出的异常,但是,我必须发送什么类型的异常到控制器,只有全局异常吗?还是SQL异常也要捕获?

我是否需要在DAO方法内部捕获异常(并创建反馈以发送给用户),还是只需将异常抛到控制器并将其留在那里处理反馈?

谢谢!

英文:

I am coding my first DAO in Java and I am wondering how to manage the exceptions that can ocurr:

My current code:

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");

	    }
	}
    }

I don't know how to manage the exceptions. The controller that calls this method has a catch block to get the exceptions from the DAO method, but, what kind of exceptions must I have to send it back to the controller, just the global one?, the SQL one too?

Have I got to catch something inside the DAO method (and create the feedback to send it to the user) or just throw the exceptions up to the controller and leave them alone with the feedback?

Thanks!!

答案1

得分: 0

通常,您会尝试封装特定的IO异常,比如来自应用程序代码的SQLException。因此,如果您正在构建一个带有一些通用DAO的简单CRUD应用程序,您可以将SQLException映射到catch子句中的更具体的异常,比如UpdateFailedException(),然后将此异常委托给Controller。根据您用于呈现逻辑的框架或库,您可以使用类似全局错误处理程序的方式将这些特定异常类型映射到HTTP响应代码(某些CRUD框架支持此功能)。另一个问题是,当没有数据被更新时,这真的是一个异常吗?如果没有数据被更新,给定的用户没有被找到,您可以通过前提条件来检查,并可能引发一个NotFoundException,该异常映射到404 Http代码,例如。或者如果用户不在数据库中,可以简单地创建一个而不引发异常。最终,它可能看起来像这样:

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;
        }
    }
}
英文:

Normally you'll try to encapsulate specific IO exceptions like the SQLException from your application code. So if you're building a simple CRUD app with some generic DAO's you could map the SQLException for example to more specific Exceptions like an UpdateFailedException() in the catch-clause and delegate this exception to the Controller. Depending on which framework or library you're using for the presentation logic, you could map this specific Exception Types to HTTP Response codes with something like a global error handler (some crud frameworks have support for this). Another question is, is it really an an Exception when no data has been updated? If no data has been updated, the given User has not been found, you could check that with a precondition and maybe raise a NotFoundException which maps to a 404 Http code for example. Or simply create one if the user is not in the database without throwing an exception. In the end it could look like something like this:

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

huangapple
  • 本文由 发表于 2020年8月4日 18:22:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/63244864.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定