快速背景:我已经基于一个简单的JSON文件构建了一个简单的Spring REST API。 Ive使用Jackson来解析JSON。 API本身可以正常工作。例如,当我输入必要的ID时,它将返回所需的字段。我在处理异常方面遇到麻烦。因此,例如,如果我输入Movies / 7(没有ID为7的电影),它只会返回一个空的正文。我需要什么代码来引发异常?请在下面找到代码:
MovieService.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. }
MovieController.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. }
就像我说的那样,代码工作得很好。但是,如果需要执行语句/ try-catch才能引发异常,该怎么办?
使用@ExceptionHandler从服务级别引发异常。