Skip to content
Advertisement

Spring Boot – throw exception or indicate item is not found

I’ve written two methods, findById searches for an item in the DB and throws an exception if the item is not found :

public Url findById(final Long id){
        return urlRepository.findById(id)
                .orElseThrow(() -> new ShortUrlNotFoundException("URL not found for the given ID"));
}

The second method, findByShortUrl searches for an item in the DB and uses the JPA method findByShortUrlIs which returns a List of size 1 if the item is found, there should never be more than 1 item in the DB for a given shortUrl :

public Optional<String> findByShortUrl(final String shortUrl){

    List<Url> urlList = urlRepository.findByShortUrlIs(shortUrl);
    if(urlList.isEmpty()){
        return Optional.empty();
    }
    else {
        return Optional.of(urlList.get(0).getLongUrl());
    }
}

I like the pattern of using a ShortUrlNotFoundException if an item is not found. Should I use it also in findByShortUrl ? Then, findByShortUrl becomes:

public Optional<String> findByShortUrl(final String shortUrl){

    List<Url> urlList = urlRepository.findByShortUrlIs(shortUrl);
    if(urlList.isEmpty()){
        throw new ShortUrlNotFoundException("URL not found for the given ID")
    }
    else {
        return Optional.of(urlList.get(0).getLongUrl());
    }
}

Advertisement

Answer

Why not using findFirst as this:

Optional<Url> findFirstByShortUrlIs(String shortUrl);

and then, you call:

public Optional<String> findByShortUrl(final String shortUrl){
        return urlRepository.findFirstByShortUrlIs(shortUrl)
                .map(Url::getLongUrl)
                .map(Optional::of)
                .orElseThrow(() -> new ShortUrlNotFoundException("URL not found for the given ID"));
}

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement