【发布时间】:2020-03-11 13:34:53
【问题描述】:
快速背景:我基于一个简单的 JSON 文件构建了一个简单的 Spring REST API。我用杰克逊来解析 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. }
就像我说的,代码运行良好。但是我需要执行什么 if 语句/try-catch 来抛出异常?
【问题讨论】:
-
#1 输入 id 7 时 response 的值是多少: Movies response = movieService.findMovie(7);空值?? #2 当您说 empty body 时,您的意思是:{},还是某种错误 500、400 等? #3 如果你允许我有一些改进
-
@JRichardsz 我刚得到一个{}。
-
当 id 为 7 时,MovieController.java 中第 21 行的 response var 为空?如果为 null ,您是否需要检测它并在您的 json 中显示自定义消息?
-
@JRichardsz 你是绝对正确的。我试图使用 try catch 块,但我使用了 if 语句来检测 null
-
那么,您的问题解决了吗?如果您将此添加到您的问题“是否有其他方法来处理错误?” ,我很乐意与您分享一些技巧