Spring Boot Rest Controller how to return different HTTP status codes?

Marco picture Marco · Jun 18, 2014 · Viewed 160.6k times · Source

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?

Answer

Jakub Kubrynski picture Jakub Kubrynski · Jun 18, 2014

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


NOTE

In Spring MVC using @ResponseBody annotation is redundant - it's already included in @RestController annotation.