Ajax Error Handling

August 18, 2012 in Ajax, JavaScript, Web 2.0

In Order to return an Ajax error from the server, you need to set the response status to 500, For example if you are working with Java Servlets, your Java Servlet will return the error as follows:

public class AjaxServlet extends HttpServlet {

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		try {
			// Do whatever you want to do
		} catch (Exception exception) {
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
	                response.getWriter().write(exception.getMessage());
	                response.flushBuffer();			
		} finally {
			// Clean up ...
		}
	}
	
}

In the client side, you can get the server error message (after checking that the readyState of the XML HTTP Request (XHR) is 4, and the status of the XHR object is 500) from the responseText of the XHR object.

If you are using a JavaScript framework (the Dojo for example): In the Dojo xhrPost API, in order to get the error message, you can get it from the ioArgs parameter of the error callback as follows:

dojo.xhrPost( {
	url: 'service URL',
	content: {},
	handleAs: 'text',
	load: function(response, ioArgs) {
		// Do something
	},
	error: function(response, ioArgs) {
		alert("Failed while doing the operation: " + ioArgs.xhr.response);
	}
});

Using the ioArgs.xhr.response, you can get the full error message from the server response, you can also get the status code from the ioArgs.xhr.status.

I wish that this advice can be useful for you in order to make Ajax error handling correctly.

Leave a reply

Your email address will not be published. Required fields are marked *

316,516 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Powered by sweet Captcha