Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java ee cdi: catch exception thrown by producer method

is it possible to catch an Exception that is thrown by a producer method in Java CDI? I have following producer method

@Produces
public User getLoggedInUser() throws UserNotLoggedInException {
    if(...){
        throw new UserNotLoggedInException();
    }
    User user = ... 
    ...
    return user;
}

and i want to inject the user object somewhere. I cannot write the method like this:

private void doSomethingWithUser(){
    try {
        User loggedInUser = user.get(); // throws exception
    } catch (UserNotLoggedInException e){  // Compiler compains
        ...
    }
}

As the compiler says that the UserNotLoggedInException is not thrown in any method. If i catch a generic Exception, everything works fine. Is there a more elegant solution to this problem?

Thanks

like image 552
bmurauer Avatar asked Sep 07 '25 12:09

bmurauer


1 Answers

As stated in CDI spec (http://docs.jboss.org/cdi/spec/1.0/html/contexts.html#contextual), exception thrown when instantiating a bean should be unchecked exception (extends RunTimeException), I guess it's not the case of your UserNotLoggedInException since complier checked it ;).

If you change your UserNotLoggedInException to make it extends RunTimeException it should work

Anyway I always find it more elegant to avoid dealing with exception. You could do something like :

@Produces
public User getLoggedInUser() throws UserNotLoggedInException {
    if(...){
        return null;
    }
    User user = ... 
    ...
    return user;
}

and check the null value later.

private void doSomethingWithUser(){
    if (user != null)
        User loggedInUser = user.get(); // throws exception

}

This work only if your user is in @Dependent scope.

The best approach in my opinion would be to avoid declaring your user as a bean but rather as a field in a bean. So this bean would always exist while its user field would be null when not logged in and not null when logged in.

Null beans are a bit weird.

like image 88
Antoine Sabot-Durand Avatar answered Sep 10 '25 05:09

Antoine Sabot-Durand