EN VI

Java - @ResponseStatus - for custom response status code?

2024-03-15 03:00:08
How to Java - @ResponseStatus - for custom response status code

I have the following line of code

@ResponseStatus(HttpStatus.OK)

Everything is simple and beautiful when the HttpStatus enum has the value I need. But today I needed status code210. And there is no such choice between HttpStatus enums value. Maybe you know a clean and tidy way how I can set the 210 status code?

Solution:

@ResponseStatus only allows you to use HttpStatus as the parameter, and HttpStatus does not allow you to provide a custom code (it's an enum, so the set of values is fixed).

To return a custom status code, you'll need to change your controller method to return ResponseEntity<YourResponseType>, and then specify the code via HttpStatusCode.valueOf:

return new ResponseEntity<String>("Hello World", HttpStatusCode.valueOf(210));

It is worth mentioning that 210 is not a status code that is defined in the HTTP spec - if possible, you'd probably be better off changing to use a status code that more accurately reflects the outcome of the API call. But I appreciate sometimes you have to do weird things when integrating systems :)

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login