JSF 2 Global exception handling, navigation to error page not happening

后端 未结 2 757
滥情空心
滥情空心 2020-11-30 07:00

I am developing a JSF 2.0 based web application. I am trying to implement a global exception handler which will redirect the user to a generic error page whenever any except

相关标签:
2条回答
  • 2020-11-30 07:32

    It's most likely because the current request is an ajax (asynchronous) request. The exception handler which you've there is designed for regular (synchronous) requests.

    The proper way to change the view in case of an ajax exception is as follows:

    String viewId = "/error.xhtml";
    ViewHandler viewHandler = context.getApplication().getViewHandler();
    context.setViewRoot(viewHandler.createView(context, viewId));
    context.getPartialViewContext().setRenderAll(true);
    context.renderResponse();
    

    This is however somewhat naive. This won't work if the ajax exception is been thrown in midst of rendering of a ajax response.

    I'd suggest to not reinvent the wheel. The JSF utility library OmniFaces has a complete working solution in flavor of FullAjaxExceptionHandler. You can find the full source code here and the showcase example here. It makes use of standard servlet API <error-page> declarations in web.xml. This way the error pages are also reusable for synchronous requests, with a little help of FacesExceptionFilter, also provided by OmniFaces.

    See also:

    • using ExternalContext.dispatch in JSF error handler causes corrupt page rendering
    • What is the correct way to deal with JSF 2.0 exceptions for AJAXified components?
    0 讨论(0)
  • 2020-11-30 07:52

    Unified way to handle both ajax and non ajax requests exception could be done simplifying your code. Instead of

    requestMap.put("exceptionMessage", t.getMessage());                 
    nav.performNavigation("/TestPRoject/error.xhtml");                 
    fc.renderResponse();
    

    is enough to use:

    fc.getExternalContext().redirect("/TestPRoject/error.xhtml");
    
    0 讨论(0)
提交回复
热议问题