我使用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.
我想根据响应对象错误动态返回 HTTPStatus 代码,如 400、400、404 等。我被提到了这个问题 -使用 spring 3 restful以编程方式更改 http 响应状态,但它没有帮助。
我有一个带有@ExceptionHandler方法的控制器类
@ExceptionHandler(CustomException.class)
@ResponseBody
public ResponseEntity<?> handleException(CustomException e) {
return new ResponseEntity<MyErrorResponse>(
new MyErrorResponse(e.getCode(), ExceptionUtility.getMessage(e.getMessage())),
ExceptionUtility.getHttpCode(e.getCode()));
}
Run Code Online (Sandbox Code Playgroud)
ExceptionUtility是一个类,我在其中使用了上面使用的两种方法(getMessage和getCode)。
public class ExceptionUtility {
public static String getMessage(String message) {
return message;
}
public static HttpStatus getHttpCode(String code) {
return HttpStatus.NOT_FOUND; //how to return status code dynamically here ?
}
}
Run Code Online (Sandbox Code Playgroud)
我不想检查 if 条件并相应地返回响应代码,有没有其他更好的方法来做到这一点?