java - 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);
}
问题是
哪一个更适合向 API 使用者(用户)响应错误消息?
抛出异常会在日志中留下错误消息。如果抛出异常更好,我应该如何避免留下来自故意抛出异常的错误消息?
谢谢
解决方案
我会考虑您的第一个示例中的一种修改方法:您抛出一个PersonNotFoundException
并添加一个异常处理程序,该处理程序将该特定异常转换为 HTTP 404 和有效负载中的适当错误消息。
例如:
@ExceptionHandler(PersonNotFoundException.class)
public ResponseEntity<Void> personNotFound()
{
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
这使您的映射代码从异常到响应分开且可重用。
推荐阅读
- django - 带有 Python 后台任务的 Django 频道
- node.js - Node.js UDP 连接太多
- c++ - Fortran 中使用 C 和 C++ 进行混合语言编程的最佳调用约定是什么?
- python - Pandas 的数据框/行索引
- pine-script - TradingView - 如何以百分比设置佣金?
- javascript - AgnualrJs - $parsers.unshift 与 $parsers.push 的区别
- arrays - 在 ruby 的所有数组中创建一个具有公共字符串的新数组
- c++ - 父类的虚函数无法工作
- tensorflow - 在 Tensorflow 的计算图中创建一个新的随机操作
- c - 打印字符串指针导致 C 中的输出损坏