HiveBrain v1.2.0
Get Started
← Back to all entries
debugjavaspringCritical

How to respond with an HTTP 400 error in a Spring MVC @ResponseBody method returning String

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
errorwithhow400methodspringmvcrespondstringhttp

Problem

I'm using Spring MVC for a simple JSON API, with a @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;
}


In the given scenario, what is the simplest and cleanest way to give a response with an 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.

Solution

Change your return type to ResponseEntity<>, and then you can use the below for 400:
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);


And for a correct request:

return new ResponseEntity<>(json,HttpStatus.OK);


After Spring 4.1 there are helper methods in ResponseEntity which could be used as:

return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);


and

return ResponseEntity.ok(json);

Code Snippets

return new ResponseEntity<>(json,HttpStatus.OK);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
return ResponseEntity.ok(json);

Context

Stack Overflow Q#16232833, score: 724

Revisions (0)

No revisions yet.