我有一个使用SpringBoot和restful构建的服务器,它是一个简单的CRUD应用程序。
我试图检查电子邮件是否已经存在,同时添加一个新的用户。
我不知道如何通过rest发送错误消息。我试过这样做:
UserController.java
//POST method for adding one user
@PostMapping("/addUser")
public ResponseEntity<User> addUser(@RequestBody User user){
User existingUser = userRepository.findByEmail(user.getEmail());
if(existingUser != null){
throw new UserAlreadyExistException("User with this email already exists");
}
return new ResponseEntity<>(service.saveUser(user), HttpStatus.OK) ;
}UserAlreadyExistException.java
public class UserAlreadyExistException extends RuntimeException{
public UserAlreadyExistException(String message) {
super(message);
}
}当我用邮递员测试它时,我得到了Error: 500 Internal Server Error
在InteliJ中,我引发了这个异常:
使用此电子邮件的com.example.library.UserAlreadyExistException:用户
已经存在
这是一种正确的做法,还是什么是最佳实践?
发布于 2020-10-03 17:55:54
你要找的是@ControllerAdvice和@ExceptionHandler。处理此类异常的方式如下:
@ControllerAdvice
@ExceptionHandler对异常进行注释。因此,添加下面的代码将捕获异常并返回自定义响应。
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler
public ResponseEntity<Object> handleAuthenticationException(UserAlreadyExistException e) {
// do what you want with e
return new ResponseEntity<>("User already exists", HttpStatus.OK);
}https://stackoverflow.com/questions/64187162
复制相似问题