I am using Spring Boot for a simple REST API and would like to return a correct HTTP statuscode if something fails.
@RequestMapping(value="/rawdata/", method = RequestMethod.PUT)
@ResponseBody
@ResponseStatus( HttpStatus.OK )
public RestModel create(@RequestBody String data) {
// code ommitted..
// how do i return a correct status code if something fails?
}
Being new to Spring and Spring Boot, the basic question is how do i return different status codes when something is ok or fails?
Spring provides a few primary ways to return custom status codes from its Controller classes: using a ResponseEntity. using the @ResponseStatus annotation on exception classes, and. using the @ControllerAdvice and @ExceptionHandler annotations.
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.
You can use the @ResponseStatus annotation. This way you can have a void method and you don't have to build a ResponseEntity. BTW returning 200 when the object exists and 204 otherwise it's a bit unusual regarding API REST design. It's common to return a 404 (not found) when the requested object is not found.
There are several options you can use. Quite good way is to use exceptions and class for handling called @ControllerAdvice
:
@ControllerAdvice
class GlobalControllerExceptionHandler {
@ResponseStatus(HttpStatus.CONFLICT) // 409
@ExceptionHandler(DataIntegrityViolationException.class)
public void handleConflict() {
// Nothing to do
}
}
Also you can pass HttpServletResponse
to controller method and just set response code:
public RestModel create(@RequestBody String data, HttpServletResponse response) {
// response committed...
response.setStatus(HttpServletResponse.SC_ACCEPTED);
}
Please refer to the this great blog post for details: Exception Handling in Spring MVC
In Spring MVC using @ResponseBody
annotation is redundant - it's already included in @RestController
annotation.
One of the way to do this is you can use ResponseEntity
as a return object.
@RequestMapping(value="/rawdata/", method = RequestMethod.PUT)
public ResponseEntity<?> create(@RequestBody String data) {
if(everything_fine) {
return new ResponseEntity<>(RestModel, HttpStatus.OK);
} else {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With