How to respond with HTTP 400 error in a Spring MVC @ResponseBody method returning String?
change your return type to ResponseEntity<>
, then you can use below for 400
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
and for correct request
return new ResponseEntity<>(json,HttpStatus.OK);
UPDATE 1
after spring 4.1 there are helper methods in ResponseEntity could be used as
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
and
return ResponseEntity.ok(json);
Something like this should work, I'm not sure whether or not there is a simpler way:
@RequestMapping(value = "/matches/{matchId}", produces = "application/json")
@ResponseBody
public String match(@PathVariable String matchId, @RequestBody String body,
HttpServletRequest request, HttpServletResponse response) {
String json = matchService.getMatchJson(matchId);
if (json == null) {
response.setStatus( HttpServletResponse.SC_BAD_REQUEST );
}
return json;
}
Not necessarily the most compact way of doing this, but quite clean IMO
if(json == null) {
throw new BadThingException();
}
...
@ExceptionHandler(BadThingException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public @ResponseBody MyError handleException(BadThingException e) {
return new MyError("That doesnt work");
}
Edit you can use @ResponseBody in the exception handler method if using Spring 3.1+, otherwise use a ModelAndView
or something.
https://jira.springsource.org/browse/SPR-6902