26/08/2021

Handling errors during a jsonRpcService call in XPages

There are three types of errors that can occur during a jsonRpcService call: client-side JS, server-side JS and the rest. Client-side error can be dealt with using the standard try/catch statement, the same goes for server-side error, but what about communication errors? For instance, how to react when the server or the HTTP task is restarted? How can the browser part of an application "see" that the session is destroyed and the communication is lost?

Browsing the internet for information about this subject revealed a low number of documents, and nothing about trapping communication errors. Strange... Shouldn't every application be prepared for a server restart or session lost? Losing a session can simply be prevented by adding a KeepSessionAlive element that communicates every x seconds with the server, so the server knows the client is still there (and vice-versa). But what if the server goes down or is restarted?

I started off with my own element to keep a session alive (simplified example):

<xp:view xmlns:xp="http://www.ibm.com/xsp/core" xmlns:xe="http://www.ibm.com/xsp/coreex">
	<xe:jsonRpcService id="HeartBeat" serviceName="desk">
		<xe:this.methods>
			<xe:remoteMethod name="heartBeat"
				script="return UserData.heartBeat()">
			</xe:remoteMethod>
		</xe:this.methods>
	</xe:jsonRpcService>
	<xp:scriptBlock id="scriptBlock1">
		<xp:this.value><![CDATA[XSP.addOnLoad(function() {
	top.deskRefresh= 60;
	setInterval(function() {
		if(--top.deskRefresh>=0)
			return;
		desk.heartBeat().addCallback(function(result) {
			if(result) {
			}
		});
		top.deskRefresh= 60;
	}, 1000);
});]]></xp:this.value>
	</xp:scriptBlock>
</xp:view>
and I tried with try/catch statements all over the place, but I couldn't detect a server restart, even though errors appeared on the browser console.

Then I looked at the prototype definition in the browser, searching for some property that's likely to have something to do with error handling. And there it was: the addErrback function! I changed my code to incorporate that function and tested it: the message displayed in the browser!


	setInterval(function() {
		if(--top.deskRefresh>=0)
			return;
		desk.heartBeat().addErrback(function(e) {
			alert("Your session has ended unexpectedly. Please reconnect.");
		}).addCallback(function(result) {
			if(result) {
			}
		});
		top.deskRefresh= 60;
	}, 1000);

Another simple solution would be to redisplay the login screen of the application, but I'll leave that to your own imagination.

© 2020 Sjef Bosman · Consultant HCL Domino/Notes
SIRET 442 133 252 00019 · tél. +33 475 252 805
sjef@bosman.fr · sjef.bosman