I often have the need to write complex functions in SSJS. It’s very powerful for manipulating data on the server, creating documents in the back-end etc. With the sessionAsSigner and sessionAsSignerWithFullAccess objects in 8.5.2, I can see me using it all the more. However, although I’ve used error handling since I started in XPages (usually with OpenLogXPages from TaskJam), that allows the system to tell me there’s an error, but I still need to tell the user there’s an error.
There are many options. One option I’ve used, for example, is:
- The SSJS button just does a partial refresh of a Hidden Input called myError.
- In my SSJS, if I hit an error I call getComponent(“myError”).value=”I’ve hit an error” to write a message to the Hidden Input.
- I add an onComplete to check document.getElementById(“myError”).value. If it’s blank, I didn’t hit an error, so I redirect.
This works, but it’s not particularly neat. And of course you need to remember to clear the value from myError at the start of your code, to handle the user making their changes and submitting again. With facesContext there is an inbuilt function for adding an error message to the page – facesContext.addMessage(). This takes two parameters. The first is a string, the id of the Display Errors (xp:messages) control. The second is a javax.faces.application.FacesMessage() object. For non-Java developers, the instinct here is to run away very quickly in any direction possible. I myself had to suppress that urge. But the javax.faces.application.FacesMessage() object takes a single parameter, a string containing the message you want to return. So you can return the error with facesContext.addMessage(“myError”, new javax.faces.application.FacesMessage(“I’ve hit an error”)). To cancel the processing of the SSJS, you can just use return false. This negates the need to use the onComplete.
So, extending that a little further, what I have is:
- The SSJS button does a partial refresh on my myError Display Errors control.
- Start my code with var msg=new javax.faces.application.FacesMessage(). This initialises a FacesMessage object that I can just pass a message to.
- If I hit an error, I call facesContext.addMessage(“myError”,msg(I’ve hit an error”)).
- Then I call return false.
- At the end of my code, if I’ve run through fine, I call return true.
- I add an onComplete to check if document.getElementById(“myError”) == undefined. If it is, I didn’t hit an error, so I redirect.
By calling facesContext.addMessage it will build up the content with multiple messages. And they’re This works nicely to write to a Display Errors control. It doesn’t seem to write to a Display Error (xp:message) control though, which would be nice. So I get all other server-side validation / conversion errors as well with it. Fortunately, in my case I’m handling those elsewhere.