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?
Example:
Controller:
@PostMapping(value = "/{id}/parents", produces = "application/json; charset=utf-8")
public ResponseEntity<AccommodationRequestDTO> 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,
"Failed to save request", e);
}
return ResponseEntity.ok(saved);
}
Service:
public AccommodationRequestDTO parents(Long id, ParentsAndUrgencyContactDTO parentsAndUrgencyContactDTO) {
Optional<AccommodationRequest> 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, " with id " + id + " not found !");
}
}
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.
@ControllerAdvice
or do you just want to know the best practice to catch handling in general? – Nevernever