【问题标题】:Spring Boot Rest Api not displaying validation messageSpring Boot Rest Api 不显示验证消息
【发布时间】:2020-09-27 05:05:30
【问题描述】:

我正在使用 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);
    }
}

以下是我尝试发送带有空 firstName 值的 JSON 时得到的响应:

{
    "timestamp": "2020-06-08T08:40:08.660+00:00",
    "status": 400,
    "error": "Bad Request",
    "message": "",
    "path": "/MVCwebshop/customer"
}

如您所见,我得到的 JSON 中的“消息”字段为空。当我尝试使用默认消息时也会发生这种情况。我该如何解决这个问题?

【问题讨论】:

标签: java spring spring-boot spring-mvc


【解决方案1】:

如果使用 Spring Boot 2.3.0.RELEASE 你必须设置

server.error.include-message=always

在您的 application.properties(或 yaml)中。

here

【讨论】:

  • 您好,我只有在将这个属性(server.error.include-message=always)放入我的 application.properties 后才会得到错误计数。properties:{“timestamp”:“2021-03-25T17:25 :49.475+00:00", "status": 400, "error": "Bad Request", "message": "对 object='memberRequestDTO' 的验证失败。错误计数: 1", "path": "/bookings /api/members/" } 我想显示该字段的错误消息,即:"@Size(min = 3, max = 50, message = "成员姓氏必须包含 3 到 50 个字符。")"我怎样才能做到这一点?
【解决方案2】:

连同上面提到的server.error.include-message=always, 您还可以将server.error.include-binding-errors=always 添加到 application.properties。 这将列出所有绑定错误以及特定消息

【讨论】:

    【解决方案3】:

    您可以添加验证查询:

    @NotEmpty(message="Please enter a first name")
    @Size(min= 1, max = 50, message="actor.firstName.size")
    private String firstName; 
    

    【讨论】:

      猜你喜欢
      • 2021-07-17
      • 1970-01-01
      • 2018-07-15
      • 1970-01-01
      • 2022-01-09
      • 2014-09-23
      • 1970-01-01
      • 2017-04-09
      • 1970-01-01
      相关资源
      最近更新 更多