Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring dynamic HttpStatus from a variable

I have an application where I am returning dynamic HttpStatus code from my controller by using ResponseEntity

return new ResponseEntity<String>("Unrecognised request.", HttpStatus.BAD_REQUEST);

The next requirement is that the response body and the status code will be loaded from database. and the code will looking something like

String msg = <<loaded from database>>;
String status = <<loaded from database>>; //type can be changed to int
return new ResponseEntity<String>(msg, <..what to do here ??..>);

Not the status code will be retrived from database as a string/integer. And as HttpStatus is an Enum, I didn't find any other way to do that.

Is there any solution to my requirement?

like image 913
BiJ Avatar asked Jul 14 '26 17:07

BiJ


1 Answers

If the status code retrieved from the database is always defined as an integer/long/numeric value, you can do similar to this:

HttpStatus.valueOf(myCoolStatusCode)

Example:

int someStatusFromDatabase = databaseService.getMeMyStatus();
String myAwsomeMessage = databaseService.getMeMyStausMessage();
return ResponseEntity.status(HttpStatus.valueOf(someStatusFromDatabase)).body(myAwsomeMessage);

Hope this helps!

like image 157
vegaasen Avatar answered Jul 17 '26 16:07

vegaasen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!