【发布时间】:2022-01-22 17:55:29
【问题描述】:
我正在开发一个 API,需要抛出如下所示的异常
"error": "sortBy parameter is invalid"
}
如果 sort by 参数不是我预先确定的值之一, 我有一些参数可以做到这一点 这是我的控制器的样子
@GetMapping("/api/posts")
public ResponseEntity<List<Post>> getPostResponse(@RequestParam String tag, Optional<String> sortBy,
Optional<String> direction) throws InvalidSortBy {
RestTemplate postResponseTemplate = new RestTemplate();
URI postUri = UriComponentsBuilder.fromHttpUrl("urlHere")
.queryParam("tag", tag)
.queryParamIfPresent("sortBy", sortBy)
.queryParamIfPresent("direction", direction)
.build()
.toUri();
ResponseEntity<PostResponse> response = postResponseTemplate.getForEntity(postUri, PostResponse.class);
ResponseEntity<List<Post>> newResponse = responseService.createResponse(response, sortBy, direction);
return newResponse;
}
}
我删除了 url,但它适用于对传入数据进行排序,但我需要验证并抛出正确的错误,我真的不确定如何以所需的格式执行它,如 json,任何帮助表示赞赏
【问题讨论】:
标签: java spring spring-boot api error-handling