在JSON错误响应中包含异常消息

时间:2020-09-09 08:14:33

标签: java spring spring-boot jpa

如果电子邮件地址已经存在,则引发一条异常消息(“ message:”具有“ + tempEmailId +”的用户已存在“)。在邮递员中进行测试时,我没有收到异常消息。请您帮我一下?问题出在哪里?enter image description here

控制器类:

@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);  // Here we declare 
}  

服务:

@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);   
    }
}

2 个答案:

答案 0 :(得分:1)

如果您使用的是Spring Boot 2.3或更高版本,则属性server.error.include-message必须设置为always

引自Spring Boot 2.3 Release Notes

更改为默认错误页面的内容

默认情况下,错误消息和所有绑定错误不再包含在默认错误页面中。这降低了将信息泄露给客户端的风险。 server.error.include-messageserver.error.include-binding-errors可以分别用来控制消息的包含和绑定错误。支持的值为alwayson-paramnever

答案 1 :(得分:0)

您可以将控制器响应包装到ResponseEntity

@PostMapping("/registeruser")
public  ResponseEntity<Object> registerUser(@RequestBody User user) throws Exception {
        String tempEmailId = user.getEmailId();
        if(tempEmailId != null && !tempEmailId.isEmpty()) {
            User userObject = service.fetchUserByEmailId(tempEmailId);
            if(userObject!=null) {
                return new ResponseEntity<>("User with "+tempEmailId+" is already exist", HttpStatus.BAD_REQUEST);
            }
        }
        return new ResponseEntity<>(service.saveUser(user), HttpStatus.OK);
}

或者(最好是变体),您可以创建特定的异常,例如UserAlreadyExistException,将其扔到控制器中并在用@RestControllerAdvice注释的类中进行拦截。 例如:

@RestControllerAdvice
public class RegistrationControllerAdvice {

    @ExceptionHandler({UserAlreadyExistException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String userAlreadyExist(UserAlreadyExistException ex, WebRequest req) {
        return ex.getMessage();
    }
}

您可以返回可序列化为JSON的任何数据结构来代替String。