How to respond with an HTTP 400 error in a Spring MVC @ResponseBody method returning String
To respond with an HTTP 400 error in a Spring MVC controller method that returns a String, you can throw a ResponseStatusException with a status of BAD_REQUEST.
Here is an example of how you can do this:
@ResponseBody
@GetMapping("/some-url")
public String someMethod() {
// some logic here
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid request");
}In this example, the ResponseStatusException is thrown with a status of BAD_REQUEST (HTTP 400) and a message. The message will be included in the response body.
Alternatively, you can use the HttpServletResponse object to set the response status and write the response body manually:
@ResponseBody
@GetMapping("/some-url")
public String someMethod(HttpServletResponse response) {
// some logic here
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return "Invalid request";
}I hope this helps! Let me know if you have any questions.