【问题标题】:Spring Boot validation error message not shown in response响应中未显示 Spring Boot 验证错误消息
【发布时间】:2022-01-09 16:41:56
【问题描述】:

我有以下简单的项目来测试 Spring Boot 验证。我使用的是 Spring Boot 2.5.6 版

pom.xml 中的验证依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

DTO 对象

import javax.validation.constraints.NotNull;

public class DepartmentDTO {

    @NotNull(message = "Department name can not be empty")
    private String name;

    // getter and setter
}

REST 控制器

@RestController
public class DepartmentResource {

    @PostMapping("/departments")
    public ResponseEntity<DepartmentDTO> createDepartment(@Valid @RequestBody DepartmentDTO department) {
        return new ResponseEntity<>(department, HttpStatus.OK);
    }
}

当我使用 null name 触发请求时,我收到错误响应,但消息丢失:

{
    "timestamp": "2021-12-03T09:13:52.729+00:00",
    "status": 400,
    "error": "Bad Request",
    "path": "/departments"
}

【问题讨论】:

标签: java spring-boot rest spring-validator


【解决方案1】:

Spring Boot 限制错误响应中包含的信息,以降低将有关应用程序的敏感信息泄露给客户端的风险。您可以通过在application.propertiesapplication.yml 中设置some properties 来显式启用响应中的其他信息。

server.error.include-binding-errors=always
server.error.include-message=always

【讨论】:

    猜你喜欢
    • 2021-07-17
    • 2017-12-28
    • 2020-06-20
    • 1970-01-01
    • 2022-06-20
    • 2022-02-03
    • 2014-09-23
    • 2020-09-27
    • 2015-12-24
    相关资源
    最近更新 更多