Spring boot 如何使用SpringBoot使用restfulAPI发送错误消息
我有一个使用SpringBoot和RESTfulAPI构建的服务器。这是一个简单的积垢应用 我试图在添加新用户时检查电子邮件是否已经存在 我不知道如何通过RESTAPI发送错误消息。我试过这样做: UserController.javaSpring boot 如何使用SpringBoot使用restfulAPI发送错误消息,spring-boot,rest,Spring Boot,Rest,我有一个使用SpringBoot和RESTfulAPI构建的服务器。这是一个简单的积垢应用 我试图在添加新用户时检查电子邮件是否已经存在 我不知道如何通过RESTAPI发送错误消息。我试过这样做: UserController.java //用于添加一个用户的POST方法 @后映射(“/addUser”) 公共响应属性addUser(@RequestBody User){ User existingUser=userRepository.findByEmail(User.getEmail());
//用于添加一个用户的POST方法
@后映射(“/addUser”)
公共响应属性addUser(@RequestBody User){
User existingUser=userRepository.findByEmail(User.getEmail());
if(existingUser!=null){
抛出新的UserAlreadyExistException(“具有此电子邮件的用户已存在”);
}
返回新的响应属性(service.saveUser(user),HttpStatus.OK);
}
UserAlreadyExistException.java
公共类UserAlreadyExistException扩展了RuntimeException{
公共用户ReadyExistException(字符串消息){
超级(信息);
}
}
当我用邮递员测试它时,我得到错误:500内部服务器错误
在InteliJ
中,我抛出了这个异常:
com.example.library.UserAlreadyExistException:此电子邮件的用户
已经存在
这是正确的方法还是最佳做法?您要查找的是
@ControllerAdvice
和@ExceptionHandler
。处理此类例外情况的方式是:
@ControllerAdvice
@ExceptionHandler
捕获异常@ControllerAdvice
公共类GlobalExceptionHandler{
@例外处理程序
公共响应handleAuthenticationException(UseralReadyExiste异常){
//用e做你想做的
返回新的响应属性(“用户已存在”,HttpStatus.OK);
}