3

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.

xploreraj
  • 3,792
  • 12
  • 33
  • 51
  • 1
    If you lookup http status code, there are many of them. 200 is successful, 302 is redirects, 404 not found, 400+ permissions, 500+ system error. I would maintain a mapping of errors, breaking it down to business and system errors. You may not want to communicate to your users of all type of errors so you will need a generic error like "error occurred ...please report this to system administrator..." – Minh Kieu May 18 '16 at 12:03
  • thanks for more insight into this. – xploreraj May 18 '16 at 12:52

3 Answers3

3

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();
xploreraj
  • 3,792
  • 12
  • 33
  • 51
2
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");
pableiros
  • 14,932
  • 12
  • 99
  • 105
Saad
  • 51
  • 3
0

There are 2 options.

1) First, check what your Server-Side is returning in the JSP/HTML. If it always returns a JSP or HTML of some kind, you can parse the Success's data object:

$.ajax({
   //...
   success: function (data, status) {

       // Any server-side exception thrown, which would return an Exception JSP in Data 
       // Let's use a substring on that page that will help us identify it
       if (data.indexOf("unexpected error") != -1) { // Assuming your Error JSP has this string
              // Display an Alert box, or any custom handling
              alert('Unexpected error occurred');
       }
       else
       {
              // ... Proceed with normal Ajax Success hander
       }

2) You can also set a ResponseCode on the Server-side, regardless of what you return:

// This is 401, but any custom code/number can be used as well
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

then in Ajax, examine it in either error or fail.

error: function (data, status, error) {
    if (status == 401) { ... }
}

or

.fail(function(jqXHR, status, errorThrown) {
     if (status == 401) { ... }
});
gene b.
  • 10,512
  • 21
  • 115
  • 227