简体   繁体   English

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

[英]Spring boot handling exception - Failed to write HTTP message

i want to handle the error for the following controller method 我想处理以下控制器方法的错误

@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);
    }

so if the id in the link nit found i'm throwing MovieNotFoundException . 因此,如果在链接nit中找到ID,则抛出了MovieNotFoundException
but spring throw the following error: 但春天抛出以下错误:

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

Your movie object is sent through a ResponseEntity object as the response . 您的电影对象通过ResponseEntity对象作为响应发送 And the response is going through HTTP as a JSON object. 响应通过HTTP作为JSON对象进行。

So your movie object needs to JSON stringify it itself. 因此,您的电影对象需要对其自身进行JSON字符串化 Java Reflection API automatically does the job for you. Java Reflection API自动为您完成这项工作。 It automatically calls getters in your Movie class and create the JSON object. 它会自动在Movie类中调用getter并创建JSON对象。

However some getters might not return the exact String representation of the relevant variable 然而,一些干将可能无法返回相关变量的准确字符串表示

Ex:- 例如: -

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

In that case HttpMessageNotWritableException could occur. 在这种情况下,可能会发生HttpMessageNotWritableException

So you can use @JsonIgnore annotation above the respective field to ignore it. 因此,您可以在相应字段上方使用@JsonIgnore批注将其忽略。 Or return exact string representation through getters . 或通过getter返回确切的字符串表示形式。

Ex:- 例如: -

@JsonIgnore
private ObjectId userId; 

Use spring's out of the box ControllerAdvice . 开箱即用,使用spring的ControllerAdvice You don't need to handle your exceptions in Controller class. 您无需在Controller类中处理异常。 Just throw any Runtime Exception where-ever it occurs (eg Service Component or DAO). 只要在任何运行时异常发生的地方都抛出该异常(例如,服务组件或DAO)。

Then write an Error Advice like this: 然后编写这样的错误通知:

@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 
    }
}

That's it. 而已。 Hope this helps. 希望这可以帮助。

Recently, I have drafted a post on How to - Spring Boot Exceptions Handling . 最近,我起草了一篇有关如何引导引导异常处理的文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM