Spring MVC:抛出异常或返回NULL实体

时间:2018-02-16 10:01:03

标签: spring spring-mvc spring-boot

CarController课程中,我有一种方法可以通过Car获取id个实例。问题是是抛出异常还是返回ResponseEntity<Car>(null, ...)

版本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;
        }
    }

}

版本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);
        }
    }

}

2 个答案:

答案 0 :(得分:0)

我建议将null元素与HTTP / 404状态代码结合使用。

如果您只是抛出异常,则错误处理最有可能产生5XX-HTTP状态代码,这意味着存在内部服务器错误。但是,在您的情况下,不应该有内部服务器错误,因为根本找不到资源。

另请参阅:https://stackoverflow.com/a/2195675/6085896(在这种情况下,问题是2XX-Status vs 4XX-Status)

答案 1 :(得分:0)

应该是

@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);
        Car car = service.getById(id);
        if (car == null) {
            return new ResponseEntity<Car>(car, headers, HttpStatus.OK);
        }
        LOG.info("Car has id {} is not exist.", id);
        return new ResponseEntity<Car>(null, headers, HttpStatus.NOT_FOUND);
    }

}

因为返回没有对象,它与Exception的含义不同,返回HttpStatus.NOT_FOUND就足够了。

相关问题