I'm using Spring MVC for a simple JSON API, with @ResponseBody
based approach like the following. (I already have a service layer producing JSON directly.)
@RequestMapping(value = "/matches/{matchId}", produces = "application/json")
@ResponseBody
public String match(@PathVariable String matchId) {
String json = matchService.getMatchJson(matchId);
if (json == null) {
// TODO: how to respond with e.g. 400 "bad request"?
}
return json;
}
Question is, in the given scenario, what is the simplest, cleanest way to respond with a HTTP 400 error?
I did come across approaches like:
return new ResponseEntity(HttpStatus.BAD_REQUEST);
...but I can't use it here since my method's return type is String, not ResponseEntity.
Not necessarily the most compact way of doing this, but quite clean IMO
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
Something like this should work, I'm not sure whether or not there is a simpler way:
I m using this in my spring boot application
With Spring Boot, I'm not entirely sure why this was necessary (I got the
/error
fallback even though@ResponseBody
was defined on an@ExceptionHandler
), but the following in itself did not work:It still threw an exception, apparently because no producible media types were defined as a request attribute:
So I added them.
And this got me through to have a "supported compatible media type", but then it still didn't work, because my
ErrorMessage
was faulty:JacksonMapper did not handle it as "convertable", so I had to add getters/setters, and I also added
@JsonProperty
annotationThen I received my message as intended
change your return type to
ResponseEntity<>
, then you can use below for 400and for correct request
UPDATE 1
after spring 4.1 there are helper methods in ResponseEntity could be used as
and
I think this thread actually has the easiest, cleanest solution, that does not sacrifice the JSON martialing tools that Spring provides:
https://stackoverflow.com/a/16986372/1278921