title: Service and controller layer exception handling design pattern
body: <p>So here is my current implementation of a rest-api endpoint, I would like to handle some kind of corner cases, for example the user or the flat is not found, so I would throw and suitable exception, but how show I handle it in the controller? For now it's not really working, if I set a not exists id it'll work as usual, and I don't get the correspondig error message.</p>
  
  <p>Service layer:</p>
  
  <pre><code>public void delete(Long flatId) {
          flatRepository.findById(flatId).ifPresentOrElse(flat -&gt; {
                      List&lt;User&gt; residents = flat.getResidents();
                      residents.forEach(resident -&gt; resident.setFlat(null));
                      flatRepository.delete(flat);
                  },
                  () -&gt; new ResourceNotFoundException("Flat " + flatId + " found"));
  
  }
  </code></pre>
  
  <p>Controller Layer:</p>
  
  <pre><code>@DeleteMapping("/flats/{flatId}")
      public void deleteFlat(@PathVariable Long flatId) {
          flatService.delete(flatId);
  }
  </code></pre>
  
  <p>GlobalExceptionHandler:</p>
  
  <pre><code>@ControllerAdvice
  @RestController
  public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
  
      @ExceptionHandler(ResourceNotFoundException.class)
      @ResponseStatus(HttpStatus.NOT_FOUND)
      public final ErrorDetails handleResourceNotFoundException(ResourceNotFoundException ex) {
          return new ErrorDetails(LocalDateTime.now(), ex.getMessage(), 404);
      }
  
      @ExceptionHandler(ResourceAlreadyDefinedException.class)
      @ResponseStatus(HttpStatus.CONFLICT)
      public final ErrorDetails handleResourceAlreadyDefinedException(ResourceAlreadyDefinedException ex) {
          return new ErrorDetails(LocalDateTime.now(),  ex.getMessage(), 409);
      }
  
  }
  </code></pre>
  
  <p>Update: I created this global exception handler, but if I send a delete request towards my api with a not exists id, it wont't send me a 404 it will just reply 200. While If I have a return value like in this case, it works as expected.</p>
  
  <pre><code>        public Flat get(Long id) {
                  return flatRepository.findById(id).orElseThrow(() -&gt; new ResourceNotFoundException("Flat " + id + " not found"));
          }
  
  
       @GetMapping("/flats/{flatId}")
          public ResponseEntity&lt;Flat&gt; getFlat(@PathVariable Long flatId) {
              return ResponseEntity.ok(flatService.get(flatId));
       }
  </code></pre>