我使用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;
}
在给定的场景中,响应HTTP 400错误的最简单、最干净的方法是什么?
我确实遇到过这样的方法:
return new ResponseEntity(HttpStatus.BAD_REQUEST);
...但我不能在这里使用它,因为我的方法的返回类型是字符串,而不是ResponseEntity。
将您的返回类型更改为ResponseEntity<>,然后您可以使用下面的400:
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
对于正确的请求:
return new ResponseEntity<>(json,HttpStatus.OK);
Spring 4.1之后,ResponseEntity中有了帮助方法,可以用作:
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
and
return ResponseEntity.ok(json);
这里有一个不同的方法。创建一个带有@ResponseStatus注解的自定义Exception,如下所示。
@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "Not Found")
public class NotFoundException extends Exception {
public NotFoundException() {
}
}
需要的时候扔出去。
@RequestMapping(value = "/matches/{matchId}", produces = "application/json")
@ResponseBody
public String match(@PathVariable String matchId) {
String json = matchService.getMatchJson(matchId);
if (json == null) {
throw new NotFoundException();
}
return json;
}
另一种方法是使用@ExceptionHandler和@ControllerAdvice将所有处理程序集中在同一个类中。如果不是,则必须将处理程序方法放入希望为其管理异常的每个控制器中。
你的处理程序类:
@ControllerAdvice
public class MyExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(MyBadRequestException.class)
public ResponseEntity<MyError> handleException(MyBadRequestException e) {
return ResponseEntity
.badRequest()
.body(new MyError(HttpStatus.BAD_REQUEST, e.getDescription()));
}
}
您的自定义异常:
public class MyBadRequestException extends RuntimeException {
private String description;
public MyBadRequestException(String description) {
this.description = description;
}
public String getDescription() {
return this.description;
}
}
现在,您可以从任何控制器抛出异常,并且可以在通知类中定义其他处理程序。