[英]Java throwing wrong exception
我创建了2个自定义异常,以处理将新用户创建并持久存储到数据库的情况。 电子邮件(用户名)是唯一ID,因此,如果重复电子邮件,则应抛出异常,因为唯一ID已经存在。 我也在进行密码确认匹配。 此确认匹配还将引发密码不匹配的自定义异常。 这两个部分可以正确地彼此独立地工作,但是,当我将所有内容放在一起进行测试时,如果密码确认失败,则抛出用户名已存在异常而不是密码不匹配异常。 为什么?
我尝试重新排序代码,但这似乎无关紧要。 我也尝试过if / else,而不是if if / else却得到了相同的结果
//Username(email) must be unique
try {
//password and confirm password must match
if (!newGcUser.getPassword().equals(newGcUser.getConfirmPassword())) {
throw new PasswordMatchException("password and confirm password does not match");
}
//if passwords match - persist to DB
newGcUser.setPassword(bCryptPasswordEncoder.encode(newGcUser.getPassword()));
//Do NOT persist or show the confirm Password
newGcUser.setConfirmPassword("");
//set user
newGcUser.setName(newGcUser.getUsername());
return userRepository.save(newGcUser);
} catch (Exception e) {
throw new UsernameAlreadyExistsException("Username: '" + newGcUser.getUsername() + "' already exists.");
}
}
我正在使用邮递员进行测试。 如果我测试一封电子邮件,但我知道该电子邮件未注册并且密码不匹配,则会收到UsernameAlreadyExistsException消息,而不是PasswordMatchException
发生这种情况是因为您的try {} catch (Exception e) {}
块正在捕获您要在该块中引发的异常,将异常抛出到try catch
块之外,并且它应该可以工作catch:
// password and confirm password must match
if (!newGcUser.getPassword().equals(newGcUser.getConfirmPassword())) {
throw new PasswordMatchException("password and confirm password does not match");
}
// Username(email) must be unique
try {
// if passwords match - persist to DB
newGcUser.setPassword(bCryptPasswordEncoder.encode(newGcUser.getPassword()));
// Do NOT persist or show the confirm Password
newGcUser.setConfirmPassword("");
// set user
newGcUser.setName(newGcUser.getUsername());
return userRepository.save(newGcUser);
} catch (Exception e) {
throw new UsernameAlreadyExistsException("Username: '" + newGcUser.getUsername() + "' already exists.");
}
(或者捕获一个不太通用的异常,例如从userRepository.save
抛出的异常并userRepository.save
并重新抛出,那么它只会捕获该异常,而不是所有异常)
发生这种情况是因为您的PasswordMatchException
扩展了Exception
并且您的catch块正在捕获它并抛出UsernameAlreadyExistsException
。
减少代码以说明我的观点:
try {
throw new PasswordMatchException();
} catch(Exception e) {
throw new UsernameAlreadyExistsException();
}
如果不了解您的代码会抛出哪种异常,您可能有两种解决方案:
1)捕获比Exception
更具体的内容。
2)将密码检查移到try / catch块之外。
建议采用不同的方法并将其模块化:
private void matchPassword(..newGcUser..) throws PasswordMatchException{
// password and confirm password must match
if (!newGcUser.getPassword().equals(newGcUser.getConfirmPassword())) {
throw new PasswordMatchException("password and confirm password does not match");
}
}
持久方法应捕获特定异常:
// Username(email) must be unique
try {
// if passwords match - persist to DB
...
return userRepository.save(newGcUser);
} catch (DataIntegrityViolationException e) {
throw new UsernameAlreadyExistsException("Username: '" + newGcUser.getUsername() + "' already exists.");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.