I was able to introduce exception handling but I could only really manage to apply it to endpoints that retrieved a specific id
@Repository
public interface OrganizationRepository extends JpaRepository<Organization, Long> {
@Query("FROM Organization WHERE name =?1")
Organization findByOrganizationNameLike(@Param("name") String name);
}
// service class method
public Organization getOrganizationById(final Long id){
return organizationRepository.findById(id).orElseThrow((ResourceNotFoundException::new));
}
//related controller method
@GetMapping("/{id}")
public ResponseEntity<Organization> getOrganizationByID(@PathVariable("id") final Long id) {
return ResponseEntity.ok(organizationService.getOrganizationById(id));
}
I am not sure if it can be applied to an endpoint such as @GetMapping("/{id}/applications") which returns a list of applications associated with a particular organization's id. However, I think it should because if I enter an invalid id into the above endpoint I get a 500 error that isn't handled nicely.
I want to be able to handle the fact that if I pass an invalid organization id into an endpoint like organizations/{id}/applications the exception will be handled gracefully.
The issue as I see it seems to me that I can’t call the orElseThrow method from a custom repository method such as findById(id).
// can invoke exception handling
public Organization getOrganizationById(final Long id){
return organizationRepository.findById(id).orElseThrow((ResourceNotFoundException::new));
}
// can't invoke exception handling
public List<Application> getAllApplicationsWithOrganizationId(final Long id){
return organizationRepository.findById(id).get().getApplications();
}
Am I correct in my assumption?
Any input is greatly appreciated.