首页 > 解决方案 > Rest API 响应(异常/错误/默认)

问题描述

我想了解有关 Rest API 响应的以下案例的最佳实践。

第一段代码

@GetMapping("/person/{id}")
public ResponseEntity<Person> postPersonDetails(@PathVariable("id) Long id) {
    Person person = personService.getPersonById(id);
    if (null == person) {
       throw new ResourceNotFoundException().withMessage("PERSON_NOT_FOUND");
    }
    return new ResponseEntity<Person>(person, HttpStatus.OK);
}

第二段代码

@GetMapping("/person/{id}")
public ResponseEntity<Person> postPersonDetails(@PathVariable("id) Long id) {
    Person person = personService.getPersonById(id);
    if (null == person) {
       return new ResponseEntity<Person>(null, HttpStatus.NotFound);
    }
    return new ResponseEntity<Person>(person, HttpStatus.OK);
}

问题是

  1. 哪一个更适合向 API 使用者(用户)响应错误消息?

  2. 抛出异常会在日志中留下错误消息。如果抛出异常更好,我应该如何避免留下来自故意抛出异常的错误消息?

谢谢

标签: javarestapispring-boot

解决方案


我会考虑您的第一个示例中的一种修改方法:您抛出一个PersonNotFoundException并添加一个异常处理程序,该处理程序将该特定异常转换为 HTTP 404 和有效负载中的适当错误消息。

例如:

@ExceptionHandler(PersonNotFoundException.class)
public ResponseEntity<Void> personNotFound()
{
    return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}

这使您的映射代码从异常到响应分开且可重用。


推荐阅读