javaspring-boothttp-status-codes

HttpStatusCode in Spring Boot 3


I just migrated an application to Spring Boot 3 and before the migration I used HttpStatus to obtain more details about the error message that a certain web client returned with the gerReasonPhrase() method.

Now I find that in Spring Boot 3, HttpStatus is deprecated and I have to use HttpStatusCode instead. But HttpStatusCode does not have the getReasonPhrase() method or anything similar. Is there a way to obtain the same information as before through HttpStatusCode without having to make a status code map with its corresponding messages?

I am searching a similar method in Spring Boot 3 than the one that exists in Spring Boot 2.


Solution

  • I'm copying the top part of this answer Error Response body changed after Boot 3 upgrade

    Spring Web 6 introduced support for the "Problem Details for HTTP APIs" specification, RFC 7807

    With this, the ResponseStatusException now implements the ErrorResponse interface and extends the ErrorResponseException class.

    Having a quick look at the javadocs, we can see that all these are backed by the RFC 7807 formatted ProblemDetail body, which, as you can imagine, has the fields of the new response you're getting, and also uses the application/problem+json media type in the response.

    ResponseStatusException.getBody();
    

    returns the ProblemDetail. In the javadoc for setTitle, you'll see the value comes from HttpStatus.getReasonPhrase(). So that's how you upgrade that part to spring-boot3.

    HttpStatus.getReasonPhrase(); 
    

    in spring-boot3 becomes

    ResponseStatusException.getBody().getTitle();
    

    Also, you can use that ProblemDetail object to get the status code

    ResponseStatusException.getBody().getStatus();