Cássio
Cássio

Reputation: 329

How to show javax.faces.context.FacesContext exception message inside an alert

I have a menu item which calls a method. When it fails, I want the ajax call shows a alert with the exception message.

menu.xhtml

<rich:panelMenuItem
    id="test"
    name="test"
    label="Ajax call"
    mode="ajax">
    <a4j:ajax
        event="select"
        onerror="alert('error: #{facesContext.messageList[0]}');"
        oncomplete="alert('Success!');"
        listener="#{menuMB.someMethod()}">
    </a4j:ajax>
</rich:panelMenuItem>

MenuMB.java

public void someMethod() throws IOException {
    try {
        // method call which may fail
    } catch (Exception e) {
        FacesContext context = FacesContext.getCurrentInstance();

        FacesMessage mensagem = new FacesMessage(FacesMessage.SEVERITY_ERROR, null, e.getMessage());
        context.addMessage(null, mensagem);

        context.getExternalContext().responseSendError(HttpServletResponse.SC_PRECONDITION_FAILED, e.getMessage());
        context.responseComplete();
    }
}

When clicking the menu option:

1) If method call succeeds, it shows an alert with the message "Success!"

2) If method call fails, it shows an alert only with the message "error:". How to show the exception message?

If I don't handle exceptions on method call, the alert of oncomplete event will always be exibited, even when method call fails.


Based on Makhiel's answer, I noticed I was going in the wrong direction. So I did this:

MenuMB:

private String resultMessage;

public void someMethod() {
    resultMessage = "Any success message";

    try {
        // method call which may fail
    } catch (Exception e) {
        resultMessage = e.getMessage();
    }
}

public String getResultMessage() {
    return resultMessage;
}

menu.xhtml

<a4j:ajax
    event="select"
    oncomplete="alert('#{menuMB.resultMessage}');"
    listener="#{menuMB.someMethod()}">
</a4j:ajax>

Upvotes: 0

Views: 804

Answers (1)

Makhiel
Makhiel

Reputation: 3884

onerror is intended for handling errors in the AJAX request/response loop; a method failing in some way is generally not a good reason to abort and send an error

If you still want to do it this way onerror has access to a variable named event that contains the response. You will not have access to the FacesMessages.

Otherwise just make a flag for the operation result and use oncomplete to handle it

<a4j:ajax
    event="select"
    data="#{menuMB.operationFailed}"
    oncomplete="handle(event.data)"
    listener="#{menuMB.someMethod()}">
</a4j:ajax>

The JS code for the handle method needs to be rerendered to show the message.

Upvotes: 1

Related Questions