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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With