Recently, I was working on a grails application in which I wanted to handle session timeout when ajax request was fired. When session expires in case of normal request, the browser redirects to login page which is handled by spring security.

 

In case of Ajax request, it doesn’t redirect as it is an asynchronous request. It simply returns 401 error code.  I was using remoteLink for ajax request.  To handle error codes we can either use attribute on_Error_Code like this:


<g:remoteLink action="show" id="1" ........ on404="alert('not found');">Test 2</g:remoteLink>


<g:remoteLink action="show" id="1" ........ on401="func1();">Test 2</g:remoteLink>

or we can also use javascript to attach Ajax error event at the document level like this:


var loginPageLink = '<g:createLink controller="login" action="auth" />';

$(document).ajaxError(function (event, xhr) {
if(xhr.status=="401"){
alert("Some message...........");
document.location.href = loginPageLink;
}

 

This approach is better as it eliminates code redundancy.  This code snippet can be added in a layout/layouts so that it can be included in gsp pages.

 

401 is choosen to be the most appropriate error code for session timeout. 419 Authentication Timeout may look more relevant but it is not a part of HTTP standard yet.

 

Hope it helps!