我使用Spring MVC作为一个简单的JSON API,@ResponseBody基于以下方法.(我已经有一个直接生成JSON的服务层.)
@RequestMapping(value = "/matches/{matchId}", produces = "application/json")
@ResponseBody
public String match(@PathVariable String matchId) {
String json = matchService.getMatchJson(matchId);
if (json == null) {
// TODO: how to respond with e.g. 400 "bad request"?
}
return json;
}
Run Code Online (Sandbox Code Playgroud)
问题是,在给定的场景中,用HTTP 400错误响应的最简单,最干净的方法是什么?
我确实遇到过这样的方法:
return new ResponseEntity(HttpStatus.BAD_REQUEST);
Run Code Online (Sandbox Code Playgroud)
...但我不能在这里使用它,因为我的方法的返回类型是String,而不是ResponseEntity.