[英]Spring Boot: Failed .. write HTTP message: springframework.http.converter.HttpMessageNotWritableException
[英]Spring boot handling exception - Failed to write HTTP message
我想处理以下控制器方法的错误
@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);
}
因此,如果在链接nit中找到ID,则抛出了MovieNotFoundException
。
但春天抛出以下错误:
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对象作为响应发送 。 响应通过HTTP作为JSON对象进行。
因此,您的电影对象需要对其自身进行JSON字符串化 。 Java Reflection API自动为您完成这项工作。 它会自动在Movie类中调用getter并创建JSON对象。
然而,一些干将可能无法返回相关变量的准确字符串表示
例如: -
public String getUserId() {
return userId.toHexString();
}
在这种情况下,可能会发生HttpMessageNotWritableException 。
因此,您可以在相应字段上方使用@JsonIgnore批注将其忽略。 或通过getter返回确切的字符串表示形式。
例如: -
@JsonIgnore
private ObjectId userId;
开箱即用,使用spring的ControllerAdvice
。 您无需在Controller类中处理异常。 只要在任何运行时异常发生的地方都抛出该异常(例如,服务组件或DAO)。
然后编写这样的错误通知:
@ControllerAdvice
class MyErrorAdvice {
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) //Response Code your want to return
@ExceptionHandler({MovieNotFoundException.class})
public void handleMovieNotFoundException(MovieNotFoundException e) {
log.error("Exception : ", e);
// Options lines
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler({MyOtherException.class})
public void handleMyOtherException(MyOtherException e) {
log.error("Exception : ", e);
// Options lines
}
}
而已。 希望这可以帮助。
最近,我起草了一篇有关如何引导引导异常处理的文章 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.