Issue
My servlet code is
try{
//something
response.setStatus(201);
out.print("Data successfully saved");
}
catch(SomeException e){
response.sendError(400, e.getMessage());
}
My JQuery Ajax function has success and error blocks as follows:
$.ajax({
type:'POST',
data: {
//some data to be passed
},
dataType: 'text',
url:'AjaxController',
success: function(response){
alert(response);
},
error: function(jqXHR, textStatus, message) {
//error handling
},
complete: function(){
//window.location.reload(true);
}
});
The exception in servlet can have different messages, so my intention is just to pass on the status code and the message to client, so that it can be displayed in a span.
In case of success, the success block is receiving the response and I saw that anything I write in out.print()
is coming inside it.
But in case of error to show up the message, I have two options:
Writing same as success to
out.print
and in success block in the Ajax function, write multiple checks with status code and decide whether to show a success message or a error message. I am not favouring this because I feel its tightly coupled and still implementing bad requests or exceptions as successful operation.Using
response.sendError(status_code::int, e.getMessage()::String)
Even though this make sure the error block in Ajax is invoked, but thesendError
API creates a HTML page, puts in my message and sends it, which I can not directly access. So in AJAX, I will be forced to write a parser to get the exception message. This is also NO NO in my mind.
How can I achieve this exception handling?
I have tried to explain in best possible manner, let me know if more info needed. Its a simple API, client makes call to servlet with form data, which is either created/updated in server or is failed if some conditions do not match. And in a span, that success or exception information is displayed, in same form page.
Solution
I have tried this and found that exceptions with status 400 is now coming in error block and i was able to retrieve the message with jqXHR.responseText
inside error block. I just did:
response.setStatus(400);
out.print(e.getMessage());
out.flush();
Answered By - xploreraj