简体   繁体   中英

Handling exception in Jquery AJAX response from Servlet

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:

  1. 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.

  2. Using response.sendError(status_code::int, e.getMessage()::String) Even though this make sure the error block in Ajax is invoked, but the sendError 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.

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();
var response = $.parseHTML(xhr.responseText);
if(xhr.status == 400) {
    alert($(response).filter( 'h1' ).text());
}

You can use the code from above to filter the status code and then print the modified message sent from server.

JSP may look like this

response.sendError(400, "Length too long");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM