Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 279
Jonik Avatar asked Apr 26 '13 09:04

Jonik


People also ask

What is @ResponseBody annotation in Spring?

The @ResponseBody annotation tells a controller that the object returned is automatically serialized into JSON and passed back into the HttpResponse object.

How do I set a response status code in Spring?

Sending Specific Response Status Codes The very basic way of sending response status is to use ResponseEntity object, which is returned by a controller. Controller can set a specific response status in the Response. Alternatively, we can use @ResponseStatus annotation to specify the desired status code.

What is use of response body in Spring boot?

@ResponseBody is a Spring annotation which binds a method return value to the web response body. It is not interpreted as a view name. It uses HTTP Message converters to convert the return value to HTTP response body, based on the content-type in the request HTTP header.


1 Answers

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); 
like image 107
Bassem Reda Zohdy Avatar answered Oct 21 '22 09:10

Bassem Reda Zohdy