我想创建一个表单,我可以提交它并将数据存储在 h2 中。如果电子邮件地址已经在 h2 中,则抛出异常。我有四个包(控制器、模型、服务、存储库)。当我使用 h2 中已经存在的电子邮件时,我没有收到异常消息。你能帮我解决问题吗?
控制器类:
@RestController
public class RegistrationController {
@Autowired
private RegistrationService service;
@PostMapping("/registeruser")
public User registerUser(@RequestBody User user) throws Exception {
String tempEmailId = user.getEmailId();
if(tempEmailId !=null && !"".equals(tempEmailId)) {
User userObject = service.fetchUserByEmailId(tempEmailId);
if(userObject!=null) {
throw new Exception("User with "+tempEmailId+" is already exist");
}
}
User userObject = null;
userObject = service.saveUser(user);
return userObject;
}
存储库:
public interface RegistrationRepository extends JpaRepository<User, Integer> {
public User findByEmailId(String emailId);
}
服务:
@Service
public class RegistrationService {
@Autowired
private RegistrationRepository repo;
public User saveUser(User user) {
return repo.save(user);
}
public User fetchUserByEmailId(String email) {
return repo.findByEmailId(email);
}
}
这是 JSON 响应,所以我希望打印我的消息,但不知何故没有发生:
{
"timestamp": "2020-08-26T06:28:01.369+00:00",
"status": 500,
"error": "Internal Server Error",
"message": "",
"path": "/registeruser"
}