我正在使用Spring Boot开发一个小型的REST API。我正在我的实体类中使用验证注释:
@NotEmpty(message="Please enter a first name")
private String firstName;
这是我的控制器和服务:
@RestController
public class CustomerController {
@Autowired
private CustomerService userService;
@PostMapping("/customer")
@ResponseStatus(HttpStatus.CREATED)
public Customer postUser (@RequestBody @Valid Customer customer){
return userService.save(customer);
}
}
public class CustomerService {
@Autowired
private CustomerRepository repository;
@Transactional
public Customer save ( Customer customer){
return repository.save(customer);
}
}
这是我尝试发送具有空名字值的 JSON 时得到的响应:
{
"timestamp": "2020-06-08T08:40:08.660+00:00",
"status": 400,
"error": "Bad Request",
"message": "",
"path": "/MVCwebshop/customer"
}
如您所见,我得到的JSON中的“消息”字段为空。当我尝试使用默认消息时,也会发生这种情况。我该如何解决这个问题?
如果使用Spring Boot 2.3.0 .版本,您必须设置
server.error.include-message=always
在您的应用程序属性(或 YAML)中。
看这里
除了上面提到的server.error.include-消息=总是
,您还可以添加server.error.include-绑定-错误=总是
application.properties.这将列出所有绑定错误,以及特定的消息
您可以添加验证查询:
@NotEmpty(message="Please enter a first name")
@Size(min= 1, max = 50, message="actor.firstName.size")
private String firstName;