How to make so, that exceptions don't thrown in Enum.valuesOf()?

Viewed 97

I have class BookSpecBuider that create JPA Specification from dto.

BookSpecBuider class:

public class BookSpecBuilder {
    public Specification<Book> getSpec(BookSearchDto bookSearchDto) {
        return (root, query, builder) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (bookSearchDto.getGenre() != null) {
                predicates.add(root.get("genre").in(bookSearchDto.getGenre()));
            }
// another conditions

Genre is enum-class, so I had problem that in my BookSearchDto Genre is String and it had problem with mapping.

I change it in my if-block:

predicates.add(root.get("genre").in(Genre.valueOf(bookSearchDto.getGenre())));

But now I have problem with exceptions, if I get String of Genre, that my enum doesn't have. What is the best way to avoid this problem?

1 Answers

I would suggest create another enum entry called Unknown (or any name) and create a new static method call .of() (or any name that you preferred) inside your Genre enum,

enum Genre {    
    public static Genre of(String genre) {
        for(Genre g : values()) {
            if (g.name().equalsIgnoreCase(genre)) {
                return g;
            }
        }
        return Unknown;
    }
}

Then this will avoid unnecessary exception.

Related