Handling exception in Jquery AJAX response from Servlet
<p><strong>My servlet code is</strong> </p>

<pre><code>try{
    //something
    response.setStatus(201);
    out.print("Data successfully saved");
}
catch(SomeException e){
    response.sendError(400, e.getMessage());
}
</code></pre>

<p><strong>My JQuery Ajax function has success and error blocks as follows:</strong></p>

<pre><code>$.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);
    } 
});
</code></pre>

<p>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 <code>out.print()</code> is coming inside it.</p>

<p>But in case of error to show up the message, I have two options:</p>

<ol>
<li><p>Writing same as success to <code>out.print</code> 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.</p></li>
<li><p>Using <code>response.sendError(status_code::int, e.getMessage()::String)</code>
Even though this make sure the error block in Ajax is invoked, but the <code>sendError</code> 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.</p></li>
</ol>

<p>How can I achieve this exception handling?</p>

<p>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.</p>