首页 > 解决方案 > ResponseEntity Api 在 REST API 中添加自定义错误消息

问题描述

我目前正在使用 Spring Rest Api,并且我正在使用 ResponseEntity API 向调用者返回响应。

我想知道如何使用以下配置呈现带有错误消息的响应:

@GetMapping
ResponseEntity<Page<Users>>  getUsers(){
try {
            usersValidationService.validate(researchCriteria);
        }catch(ValidationException e){
            return ResponseEntity.noContent().build();// here i want to return an empty list with the custom error message
        }
        return ResponseEntity.ok(repoUsers.findAll(criteresRecherche.toSpecifications(service), page));

}

标签: java

解决方案


而不是使用

return ResponseEntity.noContent().build();

试试下面:

<Page<Users>> list = ... // create a empty list and add custom message according to your class <Page<Users>> 
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(list);

推荐阅读