java - Jackson Json Parser-如何处理未找到值的异常
问题描述
快速背景:我基于一个简单的 JSON 文件构建了一个简单的 Spring REST API。我用杰克逊来解析 JSON。API 本身运行良好。例如,当我输入必要的 ID 时,它会返回所需的字段。我在异常处理方面遇到了麻烦。因此,如果我输入 movies/7 例如(没有 ID 为 7 的电影),它只会返回一个空正文。我需要什么代码才能让它抛出异常?请在下面找到代码:
电影服务.java
1. @Component
2. public class MovieService {
3.
4. ObjectMapper objectMapper = new ObjectMapper();
5.
6. public Movie findAll() throws IOException {
7.
8. byte[] jsonData = Files.readAllBytes(Paths.get("movies.json"));
9.
10. Movie movie = objectMapper.readValue(jsonData, Movie.class);
11. return movie;
12.
13. }
14.
15. public Movies findMovie(int id) throws IOException {
16.
17. byte[] jsonData = Files.readAllBytes(Paths.get("movies.json"));
18. Movie movie = objectMapper.readValue(jsonData, Movie.class);
19.
20. for (Movies movies : movie.getMovies()) {
21. if (movies.getMovieId() == id) {
22.
23. return movies;
24. }
25. }
26.
27. return null;
28. }
29. }
电影控制器.java
1. @RestController
2. public class MovieController {
3.
4. @Autowired
5. private MovieService movieService;
6.
7. @GetMapping
8. @RequestMapping("/movies")
9. public Movies[] getAll() throws IOException {
10.
11. Movies[] response = movieService.findAll().getMovies();
12. return response;
13.
14. }
15.
16. @GetMapping
17. @RequestMapping("/movies/{id}")
18. public Movies getMovie(@PathVariable int id) throws IOException {
19.
20. Movies response = movieService.findMovie(id);
21. return response;
22. }
23. }
就像我说的,代码工作得很好。但是我需要实现什么 if 语句/try-catch 才能抛出异常?
解决方案
使用@ExceptionHandler 从服务级别抛出异常。
@ExceptionHandler(NoDataException.class)
public ResponseEntity handleException(NoDataException e) {
return new ResponseEntity("No Data Found", HttpStatus.OK);
}
NoDataException
从您想要处理特定异常的任何地方抛出。
从这里阅读更多信息 - https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
推荐阅读
- named-entity-recognition - 带有自定义标签的 SparkNLP 的 NerCrfApproach
- python - 尝试将字典中的数据分配给python中的类和对象时出现KeyError
- javascript - 将嵌套的 geojson 对象解构为列表
- vbscript - 在 VBScript 中获取当前文件夹目录
- python - 如何将 3D numpy 数组转换为元组列表?
- python - 如果从 C# 控制台应用程序调用,则调用的 Arcpy 脚本不会完成
- npm - 如何解决 npm 中的无效包名错误?
- jquery - 在页面中添加两个谷歌翻译脚本,一个用于桌面,一个用于移动
- angular - Angular 我如何将 await 与 .subscribe 一起使用
- macos - 无法运行捆绑安装:捆绑器找不到 gem“捆绑器”的兼容版本