如BalusC和A.Tijms的书“ Java EE 8中的JSF权威指南”(以及类似地用Omnifaces编码)中所述,我为常规和ajax请求中发生的异常构造了以下CustomException处理程序。
public class CustomExceptionHandlerFactory extends ExceptionHandlerFactory {
public CustomExceptionHandlerFactory(ExceptionHandlerFactory wrapped) {
super(wrapped);
}
@Override
public ExceptionHandler getExceptionHandler() {
return new CustomExceptionHandler(getWrapped().getExceptionHandler());
}
private class CustomExceptionHandler extends ExceptionHandlerWrapper {
private CustomExceptionHandler(ExceptionHandler wrapped) {
super(wrapped);
}
@Override
public void handle() throws FacesException {
handleException(FacesContext.getCurrentInstance());
getWrapped().handle();
}
private void handleException(FacesContext fctx) {
Iterator<ExceptionQueuedEvent> it
= getUnhandledExceptionQueuedEvents().iterator();
if (fctx == null
|| fctx.getExternalContext().isResponseCommitted()
|| !it.hasNext()) {
return;
}
Throwable t = it.next().getContext().getException();
Throwable tc = t;
while ((tc instanceof FacesException || tc instanceof ELException)
&& tc.getCause() != null) {
tc = tc.getCause();
}
renderErrorPageView(fctx, t);
it.remove();
while (it.hasNext()) {
it.next();
it.remove();
}
}
private void renderErrorPageView(FacesContext fctx, Throwable t) {
ExternalContext ctx = fctx.getExternalContext();
String uri = ctx.getRequestContextPath()
+ ctx.getRequestServletPath();
Map<String, Object> requestMap = ctx.getRequestMap();
requestMap.put(RequestDispatcher.ERROR_REQUEST_URI, uri);
requestMap.put(RequestDispatcher.ERROR_EXCEPTION, t);
String viewId = "/view/stop_error.xhtml";
Application app = fctx.getApplication();
ViewHandler viewHandler = app.getViewHandler();
UIViewRoot viewRoot = viewHandler.createView(fctx, viewId);
fctx.setViewRoot(viewRoot);
try {
ctx.responseReset();
if (!fctx.getPartialViewContext().isAjaxRequest()) {
ctx.setResponseStatus(
HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
ViewDeclarationLanguage vdl
= viewHandler.getViewDeclarationLanguage(fctx, viewId);
vdl.buildView(fctx, viewRoot);
fctx.getPartialViewContext().setRenderAll(true);
vdl.renderView(fctx, viewRoot);
fctx.responseComplete();
}
catch (IOException e) {
throw new FacesException(e);
}
finally {
requestMap.remove(RequestDispatcher.ERROR_EXCEPTION);
}
}
}
}
在web.xml中,我有
<error-page>
<exception-type>javax.faces.application.ViewExpredException</exception-type>
<location>/faces/view/expired.xhtml</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/faces/view/stop_error.xhtml</location>
</error-page>
对于常规请求,它就像一个魅力。但是,如果ajax请求中存在(Runtime)Exception,我只会收到Java脚本警报框,该异步请求什么都不返回(在开发模式下)或什么都不返回(在生产模式下)。上面的代码可以完整运行,但是不会显示错误页面。我在Java 11下使用Tomcat 9和Mojarra 2.3.8。我在做什么错了?
我使用http://balusc.omnifaces.org/2013/01/composite-component-with-multiple-input.html中所述的复合组件进行了测试,在该组件中,我在updateDaysIfNecessary方法内引发了一个IllegalStateException,该方法通过在相应的下拉框中更改月份来触发。