gpt4 book ai didi

java - Spring Boot 处理异常 - 无法写入 HTTP 消息

转载 作者:行者123 更新时间:2023-11-29 08:27:01 25 4
gpt4 key购买 nike

我想为下面的 Controller 方法处理错误

@GetMapping(value= "search", params = {"id", "!name"})
public ResponseEntity<?> getMovieById(@RequestParam(name = "id") short id) {
Movie movie = this.movieService.getMovieById(id);
if(null == movie) {
throw new MovieNotFoundException("Unable to find moviee with id: " + id);
}
return ResponseEntity.ok(movie);
}

因此,如果找到链接中的 id,我将抛出 MovieNotFoundException
但是 spring 抛出以下错误:

Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Unable to find com.movies.mmdbapi.model.Movie with id 6; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Unable to find com.movies.mmdbapi.model.Movie with id 6

最佳答案

您的电影对象作为响应通过ResponseEntity对象发送。 响应作为JSON对象通过HTTP

因此您的电影对象需要对其本身进行JSON 字符串化Java Reflection API 会自动为您完成这项工作。它会自动调用 Movie 类中的 getter 并创建 JSON 对象。

然而一些getters可能不会返回相关变量的准确字符串表示

例如:-

public String getUserId() {
return userId.toHexString();
}

在这种情况下,可能会发生 HttpMessageNotWritableException

因此您可以在相应字段上方使用 @JsonIgnore 注释来忽略它。或者通过 getters 返回准确的字符串表示形式。

例如:-

@JsonIgnore
private ObjectId userId;

关于java - Spring Boot 处理异常 - 无法写入 HTTP 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51886968/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com