gpt4 book ai didi

JSF 2 : Is this a good approach to handle Business exceptions?

转载 作者:行者123 更新时间:2023-12-03 04:49:25 26 4
gpt4 key购买 nike

按照我之前在 Creating FacesMessage in action method outside JSF conversion/validation mechanism? 中提出的问题,我正在尝试处理从托管 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;
}

}

谢谢!

问候,金伟强

最佳答案

不知道为什么要走这条路,创建和注册您自己的异常处理程序非常简单。不过 Seam Catch 会更容易( http://seamframework.org/Seam3/CatchModulehttp://docs.jboss.org/seam/3/catch/3.0.0.Alpha1/reference/en-US/html_single/ )。我还没有 JSF 桥,但它会很容易做到。然后您所要做的就是编写一个方法来处理特定的异常,然后您就完成了!

关于JSF 2 : Is this a good approach to handle Business exceptions?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4283244/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com