mi3
mi3

Reputation: 581

Handle custom exceptions using JQuery .ajax()

Here is what my controller method looks like:

@RequestMapping(value = "/com/uData.htm", method = RequestMethod.GET)
public @ResponseBody String getData(HttpServletRequest request, 
      HttpServletResponse response, @RequestParam(value="sn", required=true) String sn, 
      @RequestParam(value="serv", required=true) String serv,
      @RequestParam(value="date", required=false) String date) throws IOException{
try {
      Srring data =...;
      if(condition == false) {
         throw new IOException("my exception message");
    }
...
...

    } catch (IOException ie) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ie.getMessage());
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.getWriter().write(ie.getMessage());
        response.flushBuffer();
    }

  return data;
}

And here is what my jQuery ajax looks like

$.ajax({
    cache: false,
    url: "/com/uData.htm",
    dataType: 'json',
    data: {"sn": sn, "serv": selServ},
    success: function(dt){
    result = dt;
  },
    error: function(jqXHR, textStatus, errorThrown) {
      if(jqXHR.responseText !== '') {
          alert(textStatus+": "+jqXHR.responseText);
    } else {
          alert(textStatus+": "+errorThrown);
       }  
     }
  });

The custom exception message that is returned is not alert in my jsp using the

alert(textStatus+": "+jqXHR.responseText);

How do I return the custom exception message ("my exception message") to the JSP?

Upvotes: 1

Views: 3832

Answers (2)

Crispy Ninja
Crispy Ninja

Reputation: 348

Try parsing the response.responseText into an object so you can pull just the ExceptionMessage (your custom exception message).

            var message = $.parseJSON(jqXHR.responseText);
            alert(textStatus+': '+message.ExceptionMessage);

My code sample uses the jQuery.parseJSON method to extract the object from the JSON.

Upvotes: 0

Aaron Digulla
Aaron Digulla

Reputation: 328614

Put it into the result of your method. Instead of returning String, return an object which has two String properties: result and exception.

That way, the client side success code can examine the exception.

Add more fields if you need more details (like exception type or additional information why the exception happened).

Upvotes: 1

Related Questions