【发布时间】:2018-07-27 05:06:16
【问题描述】:
在CarController 类中,我有一个通过id 获取Car 实例的方法。问题是是抛出异常还是返回ResponseEntity<Car>(null, ...)
VERSION 1如果汽车的Id 不存在则抛出异常
@RestController
public class CarController {
@Autowired
private CarService service;
@GetMapping("cars/{id}")
public ResponseEntity<Car> getById(@PathVariable("id") long id) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
try {
Car car = service.getById(id);
return new ResponseEntity<Car>(car, headers, HttpStatus.OK);
}
catch(AppException ae) {
LOG.error("CarService could not get car with id {}", id);
throw ae;
}
}
}
VERSION 2 如果找不到 id,则在 ResponseEntity 中返回 null Car
@RestController
public class CarController {
@Autowired
private CarService service;
@GetMapping("cars/{id}")
public ResponseEntity<Car> getById(@PathVariable("id") long id) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
try {
Car car = service.getById(id);
return new ResponseEntity<Car>(car, headers, HttpStatus.OK);
} catch (AppException ae) {
LOG.error("CarService could not get car with id {}", id);
return new ResponseEntity<Car>(null, headers, HttpStatus.NOT_FOUND);
}
}
}
【问题讨论】:
-
第二个版本更好。但是你可以这样做
return ResponseEntity.notFound().build();而不是 null
标签: spring spring-mvc spring-boot