我需要你的帮助!
在我的Web项目(基于Spring MVC)中,我使用异常指示某些验证失败,但是我不确定这样做是否正确。
例如我有这样的服务:
@Service
@Transactional
public class UserService {
@Autowired
private UserRepository userRepository;
public User createUser(UserDTO userDTO) throws IllegalArgumentExceptio {
validateUserEmail(userDTO);
return userRepository.save(new User(userDTO.getFirstName(), userDTO.getLastName(), userDTO.getEmail(), userDTO.getPassword()));
}
private void validateUserEmail(UserDTO userDTO) throws IllegalArgumentException {
String emailPattern = "^[a-z0-9-\\+]+(\\.[a-z0-9-]+)*@"
+ "[a-z0-9-]+(\\.[a-z0-9]+)*(\\.[a-z]{2,})$";
if (userDTO() == null) {
throw new IllegalArgumentException(INVALID_EMAIL_NULL.getMessage());
} else if (userDTO().length() > 25) {
throw new IllegalArgumentException(INVALID_EMAIL_LENGTH.getMessage());
} else if (!userDTO().matches(emailPattern)) {
throw new IllegalArgumentException(INVALID_EMAIL_FORMAT.getMessage());
}
}
}
我读了这篇文章。我也知道还有另一种方法是使用休眠验证器。
因此,主要问题是:哪种方法是最佳实践,为什么?
显然,使用Hibernate Validator进行Bean验证是最好的方法,因为我们不需要为最小长度/最大长度等重写大量代码。
另外,如果您自己重写最小长度/最大长度验证的逻辑,则需要进行大量测试以确保所编写的代码正确,这是必须的。
经验法则,如果已经有了一些受信任的代码,请不要尝试重新发明/重写,而只是尝试使用它,这就是所谓的DRY(请勿重复)原则,在任何编程中都非常重要
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句