简体   繁体   中英

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 .
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 . And the response is going through HTTP as a JSON object.

So your movie object needs to JSON stringify it itself. Java Reflection API automatically does the job for you. It automatically calls getters in your Movie class and create the JSON object.

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.

So you can use @JsonIgnore annotation above the respective field to ignore it. Or return exact string representation through getters .

Ex:-

@JsonIgnore
private ObjectId userId; 

Use spring's out of the box ControllerAdvice . You don't need to handle your exceptions in Controller class. Just throw any Runtime Exception where-ever it occurs (eg Service Component or 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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