我需要您的幫助!在我的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());
}
}
}
我讀過這個article。另外我知道還有一種方法是使用Hibernate Validator。
所以,主要問題是:哪一種方法是最佳實踐,爲什麼?
- 在驗證過程中拋出異常,與我一樣。
- 使用類似notification pattern的東西。
- 使用Hibernate驗證器。
我的回答有幫助嗎? – developer
@javaguy是的,它幫助了我。謝謝 – TimurJD