【问题标题】:Spring MVC: Throwing exception or returning NULL entitySpring MVC:抛出异常或返回 NULL 实体
【发布时间】: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


【解决方案1】:

应该是

@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);
    }

}

因为return no object,所以和Exception的意思不一样,return HttpStatus.NOT_FOUND就好了。

【讨论】:

  • 我相信你的意思是if (car == null)
【解决方案2】:

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

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

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

【讨论】:

    猜你喜欢
    • 2012-12-22
    • 2012-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多