'Can I apply exception handling to an enpoint like @GetMapping("organizations/{id}/applications")?

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.



Solution 1:[1]

The method orElseThrow is from Java's Optional class. If you instead call the get() method, you will no longer have an Optional, but whatever it contains.

What you could do, is use the map() method. This takes the value in the Optional and applies a method to it, or gives an empty Optional if there was no value. After map, you can again use orElseThrow. Like so:

organizationRepository.findById(id)
    .map(Organization::getApplications)
    .orElseThrow(ResourceNotFoundException::new);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1