HttpStatusCode in Spring Boot 3

2.3k views Asked by At

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.

2

There are 2 answers

0
Mark Burhans On BEST ANSWER

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 ProblemDetial. 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();
0
Cacahuet On

HttpStatus don't seems to be deprecated in the current spring version.

But there are some of the enum values that are deprecated (ex. CHECKPOINT).

Also, HttpStatus actually implements HttpStatusCode, they are not two different implementations. And so you can pass status code between them since its the same value field declared in HttpStatusCode (see mapping)