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

ehs*_*ini 3 java spring jpa spring-boot

如果电子邮件地址已存在,则抛出一条异常消息(“消息:”具有“+tempEmailId+”的用户已存在”)。当我在邮递员中测试时,我没有收到异常消息。你能帮我吗?在哪里问题?在此输入图像描述

控制器类:

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

    }
}
Run Code Online (Sandbox Code Playgroud)

存储库:

public interface RegistrationRepository extends JpaRepository<User, Integer> {

    public User findByEmailId(String emailId);  // Here we declare 
}  
Run Code Online (Sandbox Code Playgroud)

服务:

@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);   
    }
}
Run Code Online (Sandbox Code Playgroud)

Ben*_*oit 6

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

\n

引自Spring Boot 2.3 发行说明

\n
\n

对默认错误页\xe2\x80\x99s 内容的更改

\n

默认情况下,错误消息和任何绑定错误不再包含在默认错误页面中。这降低了向客户泄露信息的风险。server.error.include-message并可server.error.include-binding-errors分别用于控制消息的包含和绑定错误。支持的值为alwayson-paramnever

\n
\n