title: Spring boot exception handling best practice
body: <p>I have a simple question about exception handling.
  I currently have an application divided into multiple layers: controller, service, repository, and my question is the following: the exception handling should be done by the controller or the service?</p>
  <p>Example:</p>
  <p>Controller:</p>
  <pre><code>@PostMapping(value = &quot;/{id}/parents&quot;, produces = &quot;application/json; charset=utf-8&quot;)
  public ResponseEntity&lt;AccommodationRequestDTO&gt; resident(@PathVariable Long id, @Valid @RequestBody ParentsAndUrgencyContactDTO parentsAndUrgencyContactDTO) {
      AccommodationRequestDTO saved;
      try {
          saved = this.service.parents(id, parentsAndUrgencyContactDTO);
      } catch (Exception e) {
          throw new ResponseStatusException(
                  HttpStatus.INTERNAL_SERVER_ERROR,
                  &quot;Failed to save request&quot;, e);
      }
      return ResponseEntity.ok(saved);
  }
  </code></pre>
  <p>Service:</p>
  <pre><code>public AccommodationRequestDTO parents(Long id, ParentsAndUrgencyContactDTO parentsAndUrgencyContactDTO) {
      Optional&lt;AccommodationRequest&gt; accommodationRequest = repository.findById(id);
  
      if (accommodationRequest.isPresent()) {
          AccommodationRequest saved = accommodationRequest.get();
          Parent firstParent = parentMapper.toEntity(parentsAndUrgencyContactDTO.getFirstParent());
          Parent secondParent = parentMapper.toEntity(parentsAndUrgencyContactDTO.getSecondParent());
  
          firstParent = parentRepository.save(firstParent);
          secondParent = parentRepository.save(secondParent);
  
          saved.setFirstParent(firstParent);
          saved.setSecondParent(secondParent);
          saved = this.repository.save(saved);
  
          return mapper.toDTO(saved);
      } else {
          throw new ResponseStatusException(
                  HttpStatus.NOT_FOUND, &quot; with id &quot; + id + &quot; not found !&quot;);
      }
  
  }
  </code></pre>
  <p>What is the best practice, should I remove my try-catch from the controller and put it in my service? Because with this code my 404 Exception is overridden by the controller catch.</p>