在service编写了一个user service提供对于user的一些操作例如注册,判断是否是注册用户,以及修改密码三个方法。下面是我的代码
@Service @Transactional public class UserService { @Resource private UserDao userDao; public void regist(User user) throws UserHaveExistException, UserInfoNotCompleteException { //如果信息不全则抛出异常 if (user.getUserName() == null || user.getUserPassword() == null || user.getUserEmail() == null) { throw new UserInfoNotCompleteException(); } //如果注册的用户名已经存在则抛出异常 if (userDao.getByUserName(user.getUserName()) != null) { throw new UserHaveExistException(); } userDao.save(user); } public boolean isUser(String userName, String password) throws UserInfoNotCompleteException, UserNotExistException, PasswordNotMatchException { //如果信息不全则抛出异常 if (userName == null || password == null) { throw new UserInfoNotCompleteException(); } User target = userDao.getByUserName(userName); //如果用户名不存在则抛出异常 if (target == null) { throw new UserNotExistException(); } //如果密码不匹配则抛出异常 if (!target.getUserPassword().equals(password)) { throw new PasswordNotMatchException(); } return true; } public boolean changePassword(Serializable id, String oldPassword, String newPassword) throws UserNotExistException, PasswordNotMatchException { User user = userDao.get(id); if (user == null) { throw new UserNotExistException(); } if (!user.getUserPassword().equals(oldPassword)) { throw new PasswordNotMatchException(); } user.setUserPassword(newPassword); userDao.save(user); return true; } }
UserInfoNotCompleteException, UserNotExistException, PasswordNotMatchException这几个异常都
是我自己定义的。
上面的代码感觉异常太多了,好像有点滥用了。但是不使用异常抛出的话,对于使用该service的action如何知道调用方法里发生了什么,仅仅通过返回true和false太简单了满足不了需求。
大家都有什么看法,我这么使用异常到底对不对,有点困扰啊~~~
使用异常肯定不对。异常不是用来做这种处理的。你需要这么复杂的返回信息吗?如果需要,那么请定义一个返回信息对象。