按照我在JSF转换/验证机制之外的Action FacesMessage in action方法中的上一个问题?,我正在尝试处理从托管bean之外的业务层抛出的异常.
策略是在PhaseListener中搜索和转换业务异常以面对消息.
它按照我的预期工作,但我想知道我是刚刚重新发明轮子,还是以错误的方式做到了?
这是我的代码示例代码段:
public class BusinessExceptionHandler implements PhaseListener {
@Override
public void afterPhase(PhaseEvent phaseEvent) {
ExceptionHandler exceptionHandler = phaseEvent.getFacesContext().getExceptionHandler();
// just debugging the handled exception, nothing here
/*
for (ExceptionQueuedEvent event : exceptionHandler.getHandledExceptionQueuedEvents()) {
ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource();
System.out.println("handled exception : " + context.getException());
}*/
for (Iterator<ExceptionQueuedEvent> it = exceptionHandler.getUnhandledExceptionQueuedEvents().iterator();
it.hasNext();) {
ExceptionQueuedEvent event = it.next();
ExceptionQueuedEventContext eventContext = (ExceptionQueuedEventContext) event.getSource();
Throwable e = eventContext.getException();
System.out.println("unhandled exception : " + e);
// get the root cause exception
while (e.getCause() != null) {
e = e.getCause();
}
System.out.println("cause exception : " + e +
", cause exception is BE : " + (e instanceof BusinessException));
// handle BE
if (e instanceof BusinessException) {
BusinessException be = (BusinessException) e;
System.out.println("processing BE " + be);
FacesMessage message = Messages.getMessage(
"com.corejsf.errors",
be.getMessage(),
be.getParamValues()
);
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, message);
it.remove(); // remove the exception
// works fine without this block, if BE is thrown, always return to the original page
/*
NavigationHandler navigationHandler = context.getApplication().getNavigationHandler();
System.out.println("navigating to " + context.getViewRoot().getViewId());
navigationHandler.handleNavigation(context, context.getViewRoot().getViewId(), null);
*/
}
}
}
@Override
public void beforePhase(PhaseEvent phaseEvent) {
}
@Override
public PhaseId getPhaseId() {
return PhaseId.INVOKE_APPLICATION;
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢 !
此致,Albert Kam
您的方法是 JSF 1.x 和 JSF 2.x 异常处理方法的混合。由于您使用的是 JSF 2.x,因此我建议使用纯 JSF 2.x 方法,而无需PhaseListener使用新ExceptionHandlerAPI的帮助。
您可以在“JSF 2.0:完整参考”ViewExpiredException一书的第 282 页找到一个示例,该书可在此处在线获取(单击第一个结果链接)。
| 归档时间: |
|
| 查看次数: |
3062 次 |
| 最近记录: |