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

标签 java spring spring-boot jpa

如果电子邮件地址已经存在,则抛出异常并显示一条消息(“消息:”具有“+tempEmailId+”的用户已存在”)。我在 postman 中测试时没有收到异常消息。你能帮帮我吗? 问题出在哪里?enter image description here

Controller 类:

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

最佳答案

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

引自Spring Boot 2.3 Release Notes :

Changes to the Default Error Page’s Content

The error message and any binding errors are no longer included in the default error page by default. This reduces the risk of leaking information to a client. server.error.include-message and server.error.include-binding-errors can be used to control the inclusion of the message and binding errors respectively. Supported values are always, on-param, and never.

关于java - 在 JSON 错误响应中包含异常消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63807464/

相关文章:

java tcp服务器到多个连接

java - Spring JPA Hibernate 优点和教程

java - Spring boot 连接到使用 Arbiter 运行的 MongoDB 副本集

spring-boot - 空外键(Spring Boot、Hibernate、Postman)

java - 主键上的 JPA @AutoGenelated 对嵌套实体使用父序列/自动增量

java - struts中点击anchor标签时如何发送参数

java - 如何在 Java 中创建带有 LinkedBlockingQueue 的线程池?

Java 以特定模式拆分

java - 我无法在 java @Configuration 文件中使用 @Autowire 字段

java - 将 ''下的属性绑定(bind)到com.zaxxer.hikari.HikariDataSource失败