简体   繁体   中英

How to manage exceptions in a Java 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!!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM