Spring 响应中未显示引导验证错误消息
Spring Boot validation error message not shown in response
我有以下简单项目来测试 spring 引导验证。我正在使用 Spring 引导版本 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);
}
}
当我使用 空名称 发出请求时,我收到了错误响应,但消息丢失了:
{
"timestamp": "2021-12-03T09:13:52.729+00:00",
"status": 400,
"error": "Bad Request",
"path": "/departments"
}
Spring 引导限制错误响应中包含的信息,以降低将有关应用程序的敏感信息泄露给客户端的风险。您可以通过在 application.properties
或 application.yml
.
中设置 some properties 来显式启用响应中的附加信息
server.error.include-binding-errors=always
server.error.include-message=always
我有以下简单项目来测试 spring 引导验证。我正在使用 Spring 引导版本 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);
}
}
当我使用 空名称 发出请求时,我收到了错误响应,但消息丢失了:
{
"timestamp": "2021-12-03T09:13:52.729+00:00",
"status": 400,
"error": "Bad Request",
"path": "/departments"
}
Spring 引导限制错误响应中包含的信息,以降低将有关应用程序的敏感信息泄露给客户端的风险。您可以通过在 application.properties
或 application.yml
.
server.error.include-binding-errors=always
server.error.include-message=always