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 Dojo framework then 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.
No comments:
Post a Comment