Returning an empty ResponseEntity in Spring MVC


Posted by Steven

Spring MVC is a great way of creating REST interfaces. Many convenience classes and methods are provided, such as the Response Entity object for returning data:

  1. @GetMapping("/")
  2. public ResponseEntity<List<MyEntity>> getAll() {
  3.  
  4. return new ResponseEntity<>(myService.getAll(), HttpStatus.CREATED);
  5. }

However, there are endpoints that are not supposed to return anything, like deleting an entity. To keep the controller consistend, I prefer returning a ResponseEntity in every method. For methods that don't return anything, the Void-object has to be used as type for the ResponseEntity:

  1. @DeleteMapping(value = "/{id}")
  2. public ResponseEntity<Void> delete(@PathVariable Long id) {
  3.  
  4. try {
  5. myService.delete(id);
  6. return new ResponseEntity<>(HttpStatus.NO_CONTENT);
  7. } catch (Exception e) {
  8. return new ResponseEntity<>(HttpStatus.UNPROCESSABLE_ENTITY);
  9. }
  10. }
Category: 
Share: