首页 > 解决方案 > 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 才能抛出异常?

标签: javajsonspringjackson

解决方案


使用@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


推荐阅读