bmu*_*uer 3 java exception java-ee cdi
是否有可能捕获Java CDI中的生产者方法抛出的异常?我有以下生产方法
@Produces
public User getLoggedInUser() throws UserNotLoggedInException {
if(...){
throw new UserNotLoggedInException();
}
User user = ...
...
return user;
}
Run Code Online (Sandbox Code Playgroud)
我想在某处注入用户对象.我不能写这样的方法:
private void doSomethingWithUser(){
try {
User loggedInUser = user.get(); // throws exception
} catch (UserNotLoggedInException e){ // Compiler compains
...
}
}
Run Code Online (Sandbox Code Playgroud)
正如编译器所说的那样,UserNotLoggedInException不会抛出任何方法.如果我抓到一个通用Exception,一切正常.这个问题有更优雅的解决方案吗?
谢谢
正如CDI规范(http://docs.jboss.org/cdi/spec/1.0/html/contexts.html#contextual)中所述,实例化bean时抛出的异常应该是未经检查的异常(extends RunTimeException),我想这不是你的UserNotLoggedInException编译器检查它的情况;).
如果你改变你的UserNotLoggedInException扩展RunTimeException它应该工作
无论如何,我总是发现它更优雅,以避免处理异常.你可以这样做:
@Produces
public User getLoggedInUser() throws UserNotLoggedInException {
if(...){
return null;
}
User user = ...
...
return user;
}
Run Code Online (Sandbox Code Playgroud)
并在以后检查空值.
private void doSomethingWithUser(){
if (user != null)
User loggedInUser = user.get(); // throws exception
}
Run Code Online (Sandbox Code Playgroud)
仅当您的用户位于@Dependent范围内时,此工作才有效.
在我看来,最好的方法是避免将用户声明为bean,而是将其声明为bean中的字段.因此,这个bean将始终存在,而其用户字段在未登录时将为null,并且在登录时不为null.
空豆有点奇怪.
| 归档时间: |
|
| 查看次数: |
1644 次 |
| 最近记录: |