如何解决如果电子邮件地址已经存在,请使用注册表,然后使用Springboot和Jpa
我想创建一个表单,可以提交它并将其存储在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"
}
解决方法
我遇到了同样的问题。我所做的不是在if条件下检查对象,而是最好尝试检查对象的属性。
例如
if(userObject.getEmailId().isEmpty()) { throw new Exception("User with "+tempEmailId+" is already exist"); }
这对我有用。
您可以配置Spring ExceptionHandler 以使用异常消息来自定义响应主体:
@ControllerAdvice
public class GlobalExceptionMapper extends ResponseEntityExceptionHandler {
@Autowired
public GlobalExceptionMapper() {
}
@ExceptionHandler(value = {Exception.class})
protected ResponseEntity<Object> handleBusinessException(Exception ex,WebRequest request) {
return handleExceptionInternal(ex,ex.getMessage(),new HttpHeaders(),HttpStatus.BAD_REQUEST,request);
}
,
如果您使用的是Spring Boot 2.3或更高版本,则必须在server.error.include-message
文件中将属性always
设置为application.properties
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。