Linking Server Side Message/Exception with AJAX request

我是研究僧i 提交于 2019-12-08 02:39:50

问题


I am making an ajax submit using Primefaces but I am having trouble linking my server side message with my ajax request. Supposed I have this button that calls an action. In my managed bean, do I need to raise an exception? How do I pass this message into my ajax request

public void checkout(ActionEvent event){
    if(expression){
        throw new CustomException("Account balance is not enough!");
    }
}

public class CustomException extends RuntimeException { 
    public CustomException(String message) {
        super(message);
    }
}

How do I handle this case? Will my onerror javascript method be able to handle this?

Also, in one case supposed DB is down then how do I handle the exception? Do I have accessed to the error message in my javascript function?

public void checkout(ActionEvent event){
    try{
        //DB is down
        if(expression){
            throw new CustomException("Account balance is not enough!");
        }
    }catch(Exception e){

    }
}

回答1:


As to your concrete question, you need to implement a custom ExceptionHandler for this which does basically the following when an exception occurs in an ajax request:

String errorPageLocation = "/WEB-INF/errorpages/500.xhtml";
context.setViewRoot(context.getApplication().getViewHandler().createView(context, errorPageLocation));
context.getPartialViewContext().setRenderAll(true);
context.renderResponse();

This is not exactly trivial if you want to take web.xml error pages into account. You'd need to parse the entire web.xml for this to find the error page locations. The OmniFaces utility library has exactly such an exception handler, the FullAjaxExceptionHandler. You can find the full source code here and the showcase example here.

As to your concrete functional requirement, I wouldn't throw an exception when there's just an user error. This is fully recoverable. You need to create and add a FacesMessage and have ajax to update the <h:messages>, <p:messages> or <p:growl>. The PrimeFaces ones support an autoUpdate="true" which would auto-update itself on ajax requests. E.g.

context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Insufficient balance", null));

with

<p:messages autoUpdate="true" />

Throwing an exception makes only sense in unrecoverable situations like as when the DB is down. Note that you usually don't throw such an exception yourself. In case of JPA it would already be thrown as PersistenceException which you in turn shouldn't catch in JSF managed bean, but just let it go.



来源:https://stackoverflow.com/questions/10699327/linking-server-side-message-exception-with-ajax-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!