java ee cdi: catch exception thrown by producer method -


is possible catch exception thrown producer method in java cdi? have following producer method

@produces public user getloggedinuser() throws usernotloggedinexception {     if(...){         throw new usernotloggedinexception();     }     user user = ...      ...     return user; } 

and want inject user object somewhere. cannot write method this:

private void dosomethingwithuser(){     try {         user loggedinuser = user.get(); // throws exception     } catch (usernotloggedinexception e){  // compiler compains         ...     } } 

as compiler says usernotloggedinexception not thrown in method. if catch generic exception, works fine. there more elegant solution problem?

thanks

as stated in cdi spec (http://docs.jboss.org/cdi/spec/1.0/html/contexts.html#contextual), exception thrown when instantiating bean should unchecked exception (extends runtimeexception), guess it's not case of usernotloggedinexception since complier checked ;).

if change usernotloggedinexception make extends runtimeexception should work

anyway find more elegant avoid dealing exception. :

@produces public user getloggedinuser() throws usernotloggedinexception {     if(...){         return null;     }     user user = ...      ...     return user; } 

and check null value later.

private void dosomethingwithuser(){     if (user != null)         user loggedinuser = user.get(); // throws exception  } 

this work if user in @dependent scope.

the best approach in opinion avoid declaring user bean rather field in bean. bean exist while user field null when not logged in , not null when logged in.

null beans bit weird.


Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -